【动态规划】HDU 1081 & XMU 1031 To the Max

题目链接:

  http://acm.hdu.edu.cn/showproblem.php?pid=1081

  http://acm.xmu.edu.cn/JudgeOnline/problem.php?id=1031

 

题目大意

  给一个n*n(n<=100)的矩阵,求一个矩形覆盖的值最大是多少。

题目思路:

  【动态规划】

  二维的最大字段和。先考虑一维的情况。f[i]=max(f[i-1]+a[i],a[i])

  只要之前的部分和大于零则一起取一定比只取当前位置的要优。

  因此只要判断局部段的和是否大于零。同时每多取一个数就要更新答案。

  之后只要将一维扩展到二维就行。枚举行的始末位置。

 1 //
 2 //by coolxxx
 3 //
 4 #include<iostream>
 5 #include<algorithm>
 6 #include<string>
 7 #include<iomanip>
 8 #include<memory.h>
 9 #include<time.h>
10 #include<stdio.h>
11 #include<stdlib.h>
12 #include<string.h>
13 //#include<stdbool.h>
14 #include<math.h>
15 #define min(a,b) ((a)<(b)?(a):(b))
16 #define max(a,b) ((a)>(b)?(a):(b))
17 #define abs(a) ((a)>0?(a):(-(a)))
18 #define lowbit(a) (a&(-a))
19 #define sqr(a) ((a)*(a))
20 #define swap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))
21 #define eps (1e-8)
22 #define J 10000000
23 #define MAX 0x7f7f7f7f
24 #define PI 3.1415926535897
25 #define N 104
26 using namespace std;
27 typedef long long LL;
28 int cas,cass;
29 int n,m,lll,ans;
30 int f;
31 char map[N][N];
32 int tot[N][N];
33 int main()
34 {
35     #ifndef ONLINE_JUDGE
36 //    freopen("1.txt","r",stdin);
37 //    freopen("2.txt","w",stdout);
38     #endif
39     int i,j,k,l;
40 //    for(scanf("%d",&cas);cas;cas--)
41 //    for(scanf("%d",&cas),cass=1;cass<=cas;cass++)
42 //    while(~scanf("%s",s))
43     while(~scanf("%d",&n))
44     {
45         ans=-MAX;
46         for(i=1;i<=n;i++)
47         {
48             for(j=1;j<=n;j++)
49             {
50                 scanf("%d",&map[i][j]);
51                 tot[i][j]=tot[i-1][j]+map[i][j];
52             }
53         }
54         for(l=0;l<n;l++)
55         {
56             for(i=1;i+l<=n;i++)
57             {
58                 for(j=1,f=0;j<=n;j++)
59                 {
60                     f+=tot[i+l][j]-tot[i-1][j];
61                     ans=max(ans,f);
62                     if(f<0)f=0;
63                 }
64             }
65         }
66         printf("%d\n",ans);
67     }
68     return 0;
69 }
70 /*
71 //
72 
73 //
74 */
千万不要点

 

posted @ 2016-07-07 17:52  Cool639zhu  阅读(162)  评论(0编辑  收藏  举报