题意:求出最大子序列和
解题思路:
| i | 1 | 2 | 3 | 4 | 5 |
| map[i] | 1 | 4 | 2 | 3 | 5 |
| sum[i] | 1 | 5 | 3 | 6 | 11 |
定义一个map数组保存所输入的数据,sum数组保存到达此点的最大值(采用松弛操作),在用max找最大值。
注意:可能全为负数。我坑了3次。
连接:http://acm.hdu.edu.cn/showproblem.php?pid=1087
View Code
#include <iostream> using namespace std; int main() { int n; while(scanf("%d",&n),n) { int sum[1100]; int map[1100]; memset(map,0,sizeof(map)); for(int i=1;i<=n;i++) { scanf("%d",&map[i]); } sum[1]=map[1]; int max=map[1]; for(i=2;i<=n;i++) { sum[i] = map[i] ;//可能为负数,故用此操作 for(int j=1;j<i;j++) { if(map[i]>map[j])//限制操作 { if(sum[i]<sum[j]+map[i])//松弛操作 { sum[i]=map[i]+sum[j]; } } } if(max<sum[i]) { max=sum[i]; } } printf("%d\n",max); } return 0; }
