循环数组的最大子段和
来源:互联网 发布:淘宝drjart天猫旗舰店 编辑:程序博客网 时间:2024/05/21 14:57
题目:http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1050
题意:给定一个长度为50000的数组,求它的循环数组的最大子段和。
分析:本题与普通的最大子段和问题不同的是,最大子段和可以是首尾相接的情况,即可以循环。那么这个题目的最
大子段和有两种情况
(1)正常数组中间的某一段和最大。这个可以通过普通的最大子段和问题求出。
(2)此数组首尾相接的某一段和最大。这种情况是由于数组中间某段和为负值,且绝对值很大导致的,那么我
们只需要把中间的和为负值且绝对值最大的这一段序列求出,用总的和减去它就行了。
即,先对原数组求最大子段和,得到ans1,然后把数组中所有元素符号取反,再求最大子段和,得到ans2,
原数组的所有元素和为ans,那么最终答案就是max(ans1, ans + ans2)。
代码:
#include <iostream>#include <string.h>#include <stdio.h>using namespace std;typedef long long LL;const int N = 50005;int a[N];LL Work(int a[], int n){ LL ans = 0; LL tmp = 0; for(int i=0; i<n; i++) { if(tmp < 0) tmp = a[i]; else tmp += a[i]; ans = max(ans, tmp); } return ans;}int main(){ int n; while(scanf("%d", &n)!=EOF) { LL ans = 0; for(int i=0; i<n; i++) { scanf("%d", &a[i]); ans += a[i]; } LL ans1 = Work(a, n); for(int i=0; i<n; i++) a[i] = -a[i]; LL ans2 = Work(a, n); ans = max(ans + ans2, ans1); printf("%I64d\n", ans); } return 0;}
3 0
- 循环数组的最大子段和
- 循环数组的最大子段和
- 循环数组的最大子段和
- DP-循环数组最大子段和
- 1050 循环数组最大子段和
- 1050 循环数组最大子段和
- 循环数组最大子段和
- 1050 循环数组最大子段和
- 循环数组最大子段和
- 【hpuoj】循环数组最大子段和
- 循环数组最大子段和
- 1050 循环数组最大子段和
- 循环数组最大子段和
- 循环数组最大子段和 (dp)
- 循环数组最大子段和
- 循环数组最大子段和
- 51nod循环数组的最大子段和
- 51nod 1050 循环数组的最大子段和
- python 内置函数
- select函数(二)
- 当开发者产生一个伟大的想法之后应该做的10件事
- Codeforces Round #262 (Div. 2) B. Little Dima and Equation
- [WARALD美国职业谈]为PHD正名-说说PHD博士就业的一些问题 (全文)
- 循环数组的最大子段和
- sgu 199 Beautiful People (DP-LIS O(nlogn)算法 输出所选元素)
- 看WARALD博客 关于PHD和MASTER比较的摘要
- 欢乐暑假线上编程比赛第三题:轮换数
- 某邻居的WIFI密码
- JDBC 连接MySQL
- UVA - 657 The die is cast
- 并查集+路径压缩(poj1988)
- UVA - 1350 Pinary (递推)