【测试点5】1007 Maximum Subsequence Sum (25 分)
立志用最少的代碼做最高效的表達(dá)
PAT甲級(jí)最優(yōu)題解——>傳送門(mén)
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 -2 3 7 -21
1
2
Sample Output:
10 1 4
題意與分析
題意:
給定一個(gè)序列, 找和最大的子序列。 輸出和、子序列首位值(不是序號(hào)是值)
如果和相同,則找序號(hào)小的(見(jiàn)樣例)。
如果序列里無(wú)正數(shù),則最大值為0,輸出序列第一位與最后一位的數(shù)。
分析:
入門(mén)DP題。
如果一個(gè)子序列非負(fù),那么以它為起點(diǎn)計(jì)算累加和一定能得到更優(yōu)解。
反之,如果一個(gè)子序列為負(fù),那么需要以0為起點(diǎn)計(jì)算累加和。
測(cè)試點(diǎn)5:
樣例中只存在0和負(fù)數(shù)
因此最大累加和為0。
輸入:
5
-1 -1 0 -1 -1
輸出:
0 0 0
#include<bits/stdc++.h> using namespace std; typedef long long gg; gg a[10010] = {0}; int main() {gg n; cin >> n;gg fir = 0, las = 0, Max = 0; gg fir1 = 0, las1 = 0, Max1 = 0; //存角標(biāo),不存值。 bool flag = false; //判斷隊(duì)列是否全負(fù) for(gg i = 0; i < n; i++) {cin >> a[i];if(Max + a[i] > 0) {Max += a[i]; las = i;} else if(Max + a[i] <= 0){if(Max + a[i] == 0) flag = true;Max = 0;fir = i+1;}if(Max > Max1) {fir1 = fir; las1 = las; Max1 = Max;}}if(Max1 == 0) //如果是全負(fù)序列 printf("%d %d %d", 0, flag?0:a[0], flag?0:a[n-1]);else printf("%d %d %d", Max1, a[fir1], a[las1]);return 0; }
耗時(shí):
——愿你在被打擊時(shí),記起你的珍貴,抵抗惡意;愿你在迷茫時(shí),堅(jiān)信你的珍貴,愛(ài)你所愛(ài),行你所行,聽(tīng)從你心,無(wú)問(wèn)西東。
總結(jié)
以上是生活随笔為你收集整理的【测试点5】1007 Maximum Subsequence Sum (25 分)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 1005 Spell It Right
- 下一篇: 1008 Elevator (20 分)