Maximum sum-动态规划
2015-07-25 17:14
351 查看
A - Maximum sum
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d
& %I64u
Submit Status Practice POJ
2479
Description
Given a set of n integers: A={a1, a2,..., an}, we define a function d(A) as below:
Your task is to calculate d(A).
Input
The input consists of T(<=30) test cases. The number of test cases (T) is given in the first line of the input.
Each test case contains two lines. The first line is an integer n(2<=n<=50000). The second line contains n integers: a1, a2, ..., an. (|ai| <= 10000).There is an empty line after each case.
Output
Print exactly one line for each test case. The line should contain the integer d(A).
Sample Input
1 10 1 -1 2 2 3 -3 4 -4 5 -5
Sample Output
13
Hint
In the sample, we choose {2,2,3,-3,4} and {5}, then we can get the answer.
Huge input,scanf is recommended.
/* Author: 2486 Memory: 544 KB Time: 438 MS Language: C++ Result: Accepted */ //题目思路是从左到右分别求出它们所在位置的最大连续和,然后从右到左求出它们所在的最大连续和 //接着就是a[i]+b[i+1],a数组代表着从左到右,b代表着从右到左所以不断的比较a[0]+b[1],a[1]+b[2]求最大值即可 //怎样求解最大值(代码最后段有详解) #include <cstdio> #include <cstring> #include <algorithm> using namespace std; const int maxn=50000+5; int n,m; int a[maxn]; int dp[maxn]; int main() { scanf("%d",&n); while(n--) { scanf("%d",&m); for(int i=0; i<m; i++) { scanf("%d",&a[i]); } dp[0]=a[0]; int sum=a[0]; int ans=a[0]; for(int i=1; i<m; i++) { if(sum<0) { sum=0; } sum+=a[i]; if(sum>ans) { ans=sum; } dp[i]=ans; } sum=a[m-1]; int Max=dp[m-2]+sum; ans=a[m-1]; for(int j=m-2; j>=1; j--) { if(sum<0) { sum=0; } sum+=a[j]; if(sum>ans) { ans=sum; } Max=max(Max,dp[j-1]+ans); } printf("%d\n",Max); } return 0; }
如果当前的数据和小于零,很明显,将它加入到后面的计算中,肯定会减少最大值
很简单的道理,-1+4<0+4,如果之前的取值小于零,抛弃它,重新赋值为零
然后通过maxs不断更新当前的最大值
while(true){
scanf("%d",&a);
if(sum<0) {
sum=0;
}
sum+=a;
if(sum>maxs) {
maxs=sum;
}
}
相关文章推荐
- MySQL Bub访问地址
- iOS传值之代理传值
- 大型网站的优化
- 异常在子父类覆盖中的体现
- C语言结构体(struct)常见使用方法 blog.csdn.net/huqinwei987/article/details/23625823
- poj 3278 BFS
- lr_convert_string_encoding: 对中文进行UTF-8转码
- 智能助手相伴,享受人机温情
- 一个经典的JDBC连接MySQL的程序
- 矩阵快速幂模板
- JavaScript中你所不知道的Object(二)--Function篇
- Win7 NSIS Error: error writing temporary file的解决方法
- Kotlin for Android (II)创建一个工程
- MIUI应用权限设置
- 果新专利暗示iPhone 7设计更接近iPhone 4
- 设计模式(4): 观察者模式
- 南阳OJ 中缀式变后缀式
- android仿IOS7的两种对话框
- [知识点]网络流之Dinic算法
- 影响我学习过程的两个小机遇