maximum subarray sum

Topic link: http://exercise.acmcoder.com/online/online_judge_ques?ques_id=3352&konwledgeId=40

Problem-solving ideas: First, consider the one-dimensional case. Maximum subsequence sum of a1,a2,a3,....an. We maintain a (maximum prefix sum), when the prefix sum is less than 0, it is replaced with the current value, then the maximum value must be in these prefix sums.

Then for the two-dimensional case, we enumerate the possible starting column indices, which is a one-dimensional maximum subsequence sum problem. For example, when we select the first column and the third column, add the numbers from the first column to the third column in each row, then it is a one-dimensional problem. For the sum of a given interval, we can calculate it by prefix sum O(1), sum[i,j]=sum[0,j]-sum[0,i-1].

 1 #include <bits/stdc++.h>
 2 using namespace std;
 3 
 4 typedef long long LL;
 5 const int MAXN=100005;
 6 const LL MON7 = 1e9+7;
 7 int a[105][105];
 8 int sum[105][105];
 9 int n,m;
10 
11 void solve()
12 {
13     int ans=-2000;
14     for (int p=1;p<=m;++p)
15     {
16         for (int q=p;q<=m;q++)
17         {
18             int tmp=-2000;
19             for (int i=1;i<=n;++i)
20             {
21                 if (tmp<0) tmp=sum[i][q]-sum[i][p-1];
22                 else tmp+=sum[i][q]-sum[i][p-1];
23                 ans=max(ans,tmp);
24             }
25         }
26     }
27     printf("%d\n",ans);
28 }
29 
30 int main()
31 {
32 #ifndef ONLINE_JUDGE
33     freopen("test.txt","r",stdin);
34 #endif // ONLINE_JUDGE
35     int Case;
36     scanf("%d",&Case);
37     while (Case--)
38     {
39         scanf("%d%d",&n,&m);
40         memset(sum,0,sizeof(sum));
41         for (int i=1;i<=n;++i)
42         {
43             for (int j=1;j<=m;++j)
44             {
45                 scanf("%d",&a[i][j]);
46                 sum[i][j]=sum[i][j-1] + a[i][j];
47             }
48         }
49         solve();
50     }
51     return 0;
52 }

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324978353&siteId=291194637