1001 Problem A

1001 Problem A

题意:Given a sequence a[1],a[2],a[3]......a[n],your job is to calculate the max sum of a sub-sequence. For example, given(6,-1,5,4,-7), the max sum in this sequence is 6 + (-1) + 5 + 4 = 14.

思路:求最大值的连续子序列,对于给定的序列,从第一个数开始计算,如果到第k个数,和为负数,那么舍去前面序列,从第k+1个数重新开始计算,直到求得最大值。

感想:最大子序列,与前面的和正负有关,正则加上前面值,负则舍去,重新计算,后一步计算,与前一步有关。

#include

using namespace std;

int main(){

   int t,n,i,j,k=1,p,max;

   int a[100005],f[100005],s[100005];

   cin>>t;

   while(t--){

       cin>>n;

       for(i=1;i<=n;i++) cin>>a[i];

       f[1]=a[1]; s[1]=1;

       for(i=2;i<=n;i++){

           if(f[i-1]>=0){

                f[i]=f[i-1]+a[i];

                s[i]=s[i-1];

           }

           else{

                f[i]=a[i];

                s[i]=i;

           }

       }

       max=f[1]; p=1;

       for(j=2;j<=n;j++){

           if(f[j]>max){

                max=f[j];

               p=j;

           }

       }

       cout<<"Case "<

       k++;

       cout<

       if(t)

       cout<

    }

   return 0;

}

你可能感兴趣的:(动态规划)