Description
Input
Output
Sample Input
2 5 6 -1 5 4 -7 7 0 6 -1 1 -6 7 -5
Sample Output
Case 1: 14 1 4 Case 2: 7 1 6
解法:使用一个数组dp[i]来记录,以a[i]为字串末位的最大字串和。
如果dp[i-1]+a[i]>a[i] 则dp[i]=dp[i-1]+a[i]。否则dp[i]=a[i]实现动态规划。
效率 O(n)
<span style="font-size:24px;">#include <iostream> #include <cstring> using namespace std; int times,n,maxm; int a[100010],dp[100010],S,T,ts,tt; void solv(){ ts=tt=S=T=0; for(int i=0;i<n;i++){ if(i==0){ dp[0]=a[0]; maxm=dp[0]; } else{ if(dp[i-1]>=0){ dp[i]=dp[i-1]+a[i]; tt++; } if(dp[i-1]<0){ dp[i]=a[i]; ts=i; tt=0; } if(dp[i]>maxm){ maxm=dp[i]; S=ts; T=tt; } } } } int main(){ cin>>times; for(int i=0;i<times;i++){ memset(dp,0,sizeof(dp)); cin>>n; for(int j=0;j<n;j++) cin>>a[j]; solv(); if(i==0) cout<<"Case "<<i+1<<":\n"<<maxm<<" "<<S+1<<" "<<S+T+1<<endl; if(i!=0) cout<<"\nCase "<<i+1<<":\n"<<maxm<<" "<<S+1<<" "<<S+T+1<<endl; } return 0; } </span>
原文地址:http://blog.csdn.net/enterpine/article/details/38846079