日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

【测试点5】1007 Maximum Subsequence Sum (25 分)

發布時間:2024/2/28 编程问答 26 豆豆
生活随笔 收集整理的這篇文章主要介紹了 【测试点5】1007 Maximum Subsequence Sum (25 分) 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

立志用最少的代碼做最高效的表達


PAT甲級最優題解——>傳送門


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


題意與分析

題意:
給定一個序列, 找和最大的子序列。 輸出和、子序列首位值(不是序號是值)
如果和相同,則找序號小的(見樣例)。
如果序列里無正數,則最大值為0,輸出序列第一位與最后一位的數。

分析:
入門DP題。
如果一個子序列非負,那么以它為起點計算累加和一定能得到更優解。
反之,如果一個子序列為負,那么需要以0為起點計算累加和。

測試點5:
樣例中只存在0和負數
因此最大累加和為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; //存角標,不存值。 bool flag = false; //判斷隊列是否全負 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) //如果是全負序列 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; }

耗時:


——愿你在被打擊時,記起你的珍貴,抵抗惡意;愿你在迷茫時,堅信你的珍貴,愛你所愛,行你所行,聽從你心,無問西東。

總結

以上是生活随笔為你收集整理的【测试点5】1007 Maximum Subsequence Sum (25 分)的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。