Maximum sum-动态规划
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d
& %I64u
cid=84333#status//A/0" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" style="display:inline-block; position:relative; padding:0px; margin-right:0.1em; vertical-align:middle; overflow:visible; text-decoration:none; font-family:Verdana,Arial,sans-serif; font-size:1em; border:1px solid rgb(211,211,211); color:rgb(85,85,85)">Status
id=19810" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" style="display:inline-block; position:relative; padding:0px; margin-right:0.1em; vertical-align:middle; overflow:visible; text-decoration:none; font-family:Verdana,Arial,sans-serif; font-size:1em; border:1px solid rgb(211,211,211); color:rgb(85,85,85)">Practice
id=19810" class="ui-button ui-widget ui-state-default ui-corner-all ui-button-text-only" style="display:inline-block; position:relative; padding:0px; margin-right:0.1em; vertical-align:middle; overflow:visible; text-decoration:none; font-family:Verdana,Arial,sans-serif; font-size:1em; border:1px solid rgb(211,211,211); color:rgb(85,85,85)">POJ
2479
Description
Your task is to calculate d(A).
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
Sample Input
1 10
1 -1 2 2 3 -3 4 -4 5 -5
Sample Output
13
Hint
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; }
假设当前的数据和小于零。非常明显,将它增加到后面的计算中,肯定会降低最大值
非常easy的道理。-1+4<0+4,假设之前的取值小于零,抛弃它,又一次赋值为零
然后通过maxs不断更新当前的最大值
while(true){
scanf("%d",&a);
if(sum<0) {
sum=0;
}
sum+=a;
if(sum>maxs) {
maxs=sum;
}
}
最新文章
- SQL Server 2008 R2 安装出错:Could not open key
- DOM基础3
- 邮件群发工具(C#版)
- [C#]動態叫用Web Service
- 【BZOJ】【3261】最大异或和
- 线段树(区间合并) POJ 3667 Hotel
- Backbone的id
- HashSet的排序
- 使用VS插件在VS2012/2013上编辑和调试Quick-Cocos2d-x的Lua代码
- R︱shiny实现交互式界面布置与搭建(案例讲解+学习笔记)
- ASP.NET Core 共享第三方依赖库部署的正常打开方式
- 20181115 python-第一章学习小结part3
- Oracle绑定变量在C#.NET中的应用及意义
- 单机安装ELK
- CSS边框闪烁呼吸样式
- 转载:移动端+微信小程序实现,手机端滑动分页代码思路(ajax)
- 【Mac】使用QuickTime Player录制屏幕录像
- webpack快速入门——实战技巧:优雅打包第三方类库
- Spring+Swagger文档无法排序问题解决
- POJ3233:Matrix Power Series(矩阵快速幂+二分)