CSU - 1529 Equator —— DP 最大连续和子序列
2017-04-25 10:15
381 查看
题目链接:http://acm.csu.edu.cn/csuoj/problemset/problem?pid=1529
题解:
一个加强版的最大连续和子序列,序列可以从末尾元素转到首元素。
分两种情况:
1.最大连续和不需要尾接首,直接dp出以a[i]为结尾的最大连续和ma[i]。
2.最大连续和需要尾接首,先dp出以a[i]为结尾的最小连续和mi[i],然后再用总和sum减去mi[i],得到的即为减去中间部分的尾接首序列和(逆向思维)。最后再用max()取最大值。
代码如下:
题解:
一个加强版的最大连续和子序列,序列可以从末尾元素转到首元素。
分两种情况:
1.最大连续和不需要尾接首,直接dp出以a[i]为结尾的最大连续和ma[i]。
2.最大连续和需要尾接首,先dp出以a[i]为结尾的最小连续和mi[i],然后再用总和sum减去mi[i],得到的即为减去中间部分的尾接首序列和(逆向思维)。最后再用max()取最大值。
代码如下:
#include <iostream> #include <cstdio> #include <cstring> #include <cstdlib> #include <string> #include <vector> #include <map> #include <set> #include <queue> #include <sstream> #include <algorithm> using namespace std; #define pb push_back #define mp make_pair #define ms(a, b) memset((a), (b), sizeof(a)) //#define LOCAL #define eps 0.0000001 #define LNF (1<<60) typedef long long LL; const int inf = 0x3f3f3f3f; const int maxn = 2000000+10; const int mod = 1e9+7; LL a[maxn]; LL ma[maxn], mi[maxn]; void solve() { int n; scanf("%d",&n); LL sum = 0; for(int i = 1; i<=n; i++) scanf("%lld",&a[i]), sum += a[i]; LL now = 0; for(int i = 1; i<=n; i++)//最大连续和 { if(now>=0) ma[i] = a[i]+now, now += a[i]; else ma[i] = a[i], now = a[i]; } now = 0; for(int i = 1; i<=n; i++)//最小连续和 { if(now<= 0) mi[i] = a[i] + now, now += a[i]; else mi[i] = a[i], now = a[i]; } LL ans = ma[1]; for(int i = 1; i<=n; i++)//寻找最大值 { ans = max(ans, ma[i]); ans = max(ans, sum-mi[i]); } printf("%lld\n",ans); } int main() { #ifdef LOCAL freopen("input.txt", "r", stdin); // freopen("output.txt", "w", stdout); #endif // LOCAL int t; scanf("%d", &t); while(t--){ solve(); } return 0; }
相关文章推荐
- hdu 1159Common Subsequence(dp 最大不连续的子序列)
- CSU 1529: Equator(dp)
- poj 2479 Maximum sum(简单dp,最大连续和拓展)
- 最大连续递增子序列
- pku 2479 最大连续和的两序列 dp
- 最大连续和2——dp
- 动态规划-最长连续子序列和与最大子矩阵
- HDU1003 Max Sum(最大连续子序和、贪心、DP)
- [DP]FJSDFZOJ 1386 最大连续子段和问题
- hdu 1087 Super Jumping! Jumping! Jumping!(基础DP,最大上升子序列和)
- HDU 1087 Super Jumping! Jumping! Jumping! (线性dp 最大上升子序列)
- hdu1087 dp(最大上升子序列和)
- hdoj Max Sum Plus Plus 1024 (DP) m个连续数组最大和
- HDU 1513 Palindrome(dp最大公共子序列+滚动数组)
- POJ 1050 To the Max && POJ 2479 Maximum sum(DP最大连续子段和)
- 连续子串的最大值(经典的DP问题)
- POJ 2479 Maximum sum & POJ 2573 Max Sequence (DP,最大连续子串和)
- 一个int数组,求乘起来最大的连续子序列
- uva 242 DP 求s张邮票可以连续组合成最大面值多少的邮票
- HDU-1231,最大区间连续和总结-分治法-dp