【PAT - 甲级1007】Maximum Subsequence Sum (25分)(前缀和)
題干:
Given a sequence of?K?integers {?N?1??,?N?2??, ...,?N?K???}. A continuous subsequence is defined to be {?N?i??,?N?i+1??, ...,?N?j???} 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 Specification:
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 Specification:
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.
Sample Input:
10 -10 1 2 3 4 -5 -23 3 7 -21Sample Output:
10 1 4?題目大意:
給出長度為n的序列,求出最大子段和,并讓你輸出和的值,和子段對應左右坐標的值。
如果所有數字都<0,則輸出0和最左端最右端的值。
如果有多個符合條件的解,則輸出坐標最小的一組。
解題報告:
區間問題轉化為前綴的差。順便維護結果。
AC代碼:
#include<cstdio> #include<iostream> #include<algorithm> #include<queue> #include<stack> #include<map> #include<vector> #include<set> #include<string> #include<cmath> #include<cstring> #define FF first #define SS second #define ll long long #define pb push_back #define pm make_pair using namespace std; typedef pair<int,int> PII; const int MAX = 2e5 + 5; int n,a[MAX]; int sum[MAX],pre[MAX]; int tmpl=1,ansl=1,ansr=1,ans=-1e9; int main() {cin>>n;for(int i = 1; i<=n; i++) cin>>a[i],sum[i] = sum[i-1] + a[i];int flag = 0;for(int i = 1; i<=n; i++) {if(a[i] >= 0) flag = 1;}if(flag == 0) {printf("0 %d %d\n",a[1],a[n]);return 0;}for(int i = 1; i<=n; i++) {pre[i] = pre[i-1];int tmp = sum[i] - sum[tmpl-1];if(tmp > ans) {ans = tmp;ansl = tmpl,ansr = i;}if(sum[i] < pre[i-1]) {tmpl = i+1;pre[i] = sum[i];}}printf("%d %d %d\n",ans,a[ansl],a[ansr]);return 0 ; }?
總結
以上是生活随笔為你收集整理的【PAT - 甲级1007】Maximum Subsequence Sum (25分)(前缀和)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 信用卡审核中可以取消吗 怎样取消信用卡申
- 下一篇: 国债再现疯狂表现,利率超银行存款2.5倍