您的位置:首页 > 其它

【POJ2479】Maximum sum(动态规划,DP)

2011-05-03 15:22 309 查看
跟之前的求子段最大和差不多,不知道请看http://blog.pureisle.net/?p=266
这里求的是两个子段最大和,注意看数据,两个子段均不能为空(偶在这里多两次WA)。。。。另附POJ,discuss里边别人粘贴出来了一层循环写法。。。道理都差不多,时间也差不多。

#include <cstdio>
#include <algorithm>
using namespace std;
int a[1000001];
int res[1000001];
int main(){
freopen("1.txt","r",stdin);
int n,x;
scanf("%d",&n);
while(n--){
scanf("%d",&x);
int ans=-9999999,mymax=-9999999,temp=0;
for (int i=1;i<=x;i++){
scanf("%d",&a[i]);
res[i]=max(res[i-1]+a[i],a[i]);
}
for (int i=x;i>=2;i--){
temp +=a[i];
if(temp>mymax) mymax=temp;
if(ans<res[i-1]+mymax)
ans=res[i-1]+mymax;
if(temp<0) temp=0;
}
printf("%d/n",ans);
}
}


#include<cstdio>

int max(int x, int y ) {return x>y? x : y; }

int main()
{
int cas,n;
scanf("%d",&cas);
while ( cas -- )
{
scanf("%d",&n);
int a, b , ans, a_max,k;
a = b = a_max = 0;
ans = -99999999;
scanf("%d",&k);
b = a_max = k;
a = max(k , 0 );
for (int i = 1; i<n; i++)
{
scanf("%d",&k);
a = a + k;
if ( a < 0 ) a = 0;
b = max( b+k , a_max+k );
ans = max( ans , b);
a_max = max( a, a_max);
b = max( b , a_max);
}
printf("%d/n",ans);
}
}


做人厚道啊,转载请注明出处:三江小渡的博客
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: