Max Sum Plus Plus

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/32768 K (Java/Others)

Total Submission(s): 13462    Accepted Submission(s): 4425

 

 

Problem Description

Now I think you have got an AC inIgnatius.L's "Max Sum" problem. To be a brave ACMer, we alwayschallenge ourselves to more difficult problems. Now you are faced with a moredifficult problem.

 

Given a consecutive number sequence S1, S2,S3, S4 ... Sx, ... Sn (1 ≤ x ≤ n ≤ 1,000,000, -32768 ≤ Sx ≤ 32767). We define a function sum(i, j) = Si + ... + Sj (1 ≤ i ≤ j ≤ n).

 

Now given an integer m (m > 0), yourtask is to find m pairs of i and j which make sum(i1, j1) + sum(i2, j2) +sum(i3, j3) + ... + sum(im, jm) maximal (ix ≤ iy ≤ jx or ix ≤ jy ≤ jx is not allowed).

 

But I`m lazy, I don't want to write aspecial-judge module, so you don't have to output m pairs of i and j, justoutput the maximal summation of sum(ix, jx)(1 ≤ x ≤ m) instead.^_^

 

 

Input

Each test case will begin with two integersm and n, followed by n integers S1, S2, S3 ... Sn.

Process to the end of file.

 

 

Output

Output the maximal summation describedabove in one line.

 

 

Sample Input

1 3 1 2 3

2 6 -1 4 -2 3 -2 3

 

 

Sample Output

6

8

解題代碼:

//學習c++編程,STL queue,stack,sort函數

#include<stdio.h>

#include<algorithm>

using namespace std;

inta[1000000],b1[1000000]={0},b2[1000000]={0};//注意:一般全局的,靜態的變量所允許分配的最大空間比局部的,動態的變量的要大。

int main()

{

       intm,n,i,j,p,q,max;

       while(scanf("%d%d",&m,&n)!=EOF)

       {

             

              for(i=1;i<=n;i++)

              {

                     scanf("%d",&a[i]);

                     b1[i]=b2[i]=0;

              }

              max=0;//對每個事例初始化max

              for(i=1;i<=m;i++)

              {

                     for(j=0;j<=n;j++)

                     {

                            if(j==0)b2[j]=0;

                            elseif(i<=j)

                            {

                                   p=max+a[j];//*max_element(b1+i-1,b1+j)+a[j];也可以不用max改爲這一種算法但是會超時,在計算的時候把相應max求出來

                                   q=b2[j-1]+a[j];//沒有必要再一次重複的求max了,大大節約了時間

                                   b2[j]=p>q?p:q;

                                   max=max>b1[j]?max:b1[j];//賦值下一個b2[j]的max

                            }

                     }                  

                     for(j=0;j<=n;j++)b1[j]=b2[j];

                     max=b1[i];//賦值下一行的第一個(i==j時)b2[j]的max

              }

              printf("%d\n",*max_element(b2+m,b2+n+1));

       }

       return0;

}

1.這道題是最大字串的推廣和深入,是繼最長公共子序列之後的有一個用二維數組解決的經典的問題。

2.解題思路:設b(i,j)表示數組a的前j項中i個字段和的最大值,且第i個子段含a[j](1<=i<=m,i<=j<=n)。則所求最優值顯然爲。與最大子段和問題類似地,計算b(i,j),的遞歸式爲:

其中表示第i個子段含a[j-1],而表示第i個子段僅含a[j]。初始時,b(0,j)=0,(1jn);b(i,0)=0,(1im)。

3.,活用數學方法證明,牢記遞歸式。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章