首页 > 学院 > 开发设计 > 正文

PAT (Advanced Level) Practise 1007. Maximum Subsequence Sum (25)

2019-11-06 08:44:12
字体:
来源:转载
供稿:网友

1007. Maximum Subsequence Sum (25) 时间限制: 400 ms内存限制: 65536 kB代码长度限制: 16000 B判题程序:Standard
  Given a sequence of K integers { N1, N2, …, NK }. A continuous subsequence is defined to be { Ni, Ni+1, …, Nj } where 1 <= i <= j <= K. The Maximum Subsequence is the continuous subsequence which has the largest sum of its elements. For example, given sequence { -2, 11, -4, 13, -5, -2 }, its maximum subsequence is { 11, -4, 13 } with the largest sum being 20.  Now you are supposed to find the largest sum, together with the first and the last numbers of the maximum subsequence. Input   Each input file contains one test case. Each case occupies two lines. The first line contains a positive integer K (<= 10000). The second line contains K numbers, separated by a space. Output   For each test case, output in one line the largest sum, together with the first and the last numbers of the maximum subsequence. The numbers must be separated by one space, but there must be no extra space at the end of a line. In case that the maximum subsequence is not unique, output the one with the smallest indices i and j (as shown by the sample case). If all the K numbers are negative, then its maximum sum is defined to be 0, and you are supposed to output the first and the last numbers of the whole sequence. Examples

Input
10-10 1 2 3 4 -5 -23 3 7 -21
Output
10 1 4

  Notes    作者   CHEN, Yue

  最大子串和问题   有序列a1,...,an,记b[j]=max1≤i≤j∑k=ina[k],i≤j≤n   则最大子串和为max1≤i≤j∑k=ija[k]=max1≤j≤n{max1≤i≤ja[k]}=max1≤j≤nb[j]   当b[j−1]<0时,b[j]=b[j−1]+a[k]。否则,b[j]=a[j]。   故动态规划递推式为b[j]=max{b[j−1]+a[j],a[j]},1≤j≤n   由于递推到j时,只用到了数组bb[j−1],用一个变量保存这个值即可。如果最大子串和的结果为负数,可以确定序列a1,...,an中所以元素都为负数。

#include <iostream>#include <algorithm>#include <map>#include <vector>#include <functional>#include <string>#include <cstring>#include <queue>#include <set>#include <stack>#include <cmath>#include <cstdio>#include <sstream>#include <iomanip>using namespace std;#define IOS ios_base::sync_with_stdio(false)#define TIE std::cin.tie(0)#define MIN2(a,b) (a<b?a:b)#define MIN3(a,b) (a<b?(a<c?a:c):(b<c?b:c))#define MAX2(a,b) (a>b?a:b)#define MAX3(a,b,c) (a>b?(a>c?a:c):(b>c?b:c))typedef long long LL;typedef unsigned long long ULL;const int INF = 0x3f3f3f3f;const double PI = 4.0*atan(1.0);const double eps = 1e-6;int n, a[10005], f, sp, ep, maxs, sum;int main(){ sum = sp = ep = 0; maxs = 0xc0c0c0c0; scanf("%d", &n); for (int i = 0; i < n; i++) scanf("%d", &a[i]); for (int i = 0; i < n; i++){ if (sum < 0){ sum = a[i]; f = i; } else { sum += a[i]; } if (sum > maxs){ maxs = sum; sp = f; ep = i; } } if (maxs < 0) { maxs = 0; sp = 0; ep = n - 1; } PRintf("%d %d %d/n", maxs, a[sp], a[ep]); //system("pause");}

参考文献: 1.计算机算法设计与分析(第四版) 王晓东


上一篇:读《刻意练习》

下一篇:按键消抖

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表