HDU1231(最大连续子序列)
                                                            生活随笔
收集整理的這篇文章主要介紹了
                                HDU1231(最大连续子序列)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.                        
                                給定K個整數的序列{ N1, N2, ..., NK },其任意連續子序列可表示為{ Ni, Ni+1, ...,
 Nj },其中 1 <= i <= j <= K。最大連續子序列是所有連續子序列中元素和最大的一個,
 例如給定序列{ -2, 11, -4, 13, -5, -2 },其最大連續子序列為{ 11, -4, 13 },最大和
 為20。
 在今年的數據結構考卷中,要求編寫程序得到最大和,現在增加一個要求,即還需要輸出該
 子序列的第一個和最后一個元素。
Input
測試輸入包含若干測試用例,每個測試用例占2行,第1行給出正整數K( < 10000 ),第2行給出K個整數,中間用空格分隔。當K為0時,輸入結束,該用例不被處理。
Output
對每個測試用例,在1行里輸出最大和、最大連續子序列的第一個和最后一個元
 素,中間用空格分隔。如果最大連續子序列不唯一,則輸出序號i和j最小的那個(如輸入樣例的第2、3組)。若所有K個元素都是負數,則定義其最大和為0,輸出整個序列的首尾元素。
Sample Input
6 -2 11 -4 13 -5 -2 10 -10 1 2 3 4 -5 -23 3 7 -21 6 5 -8 3 2 5 0 1 10 3 -1 -5 -2 3 -1 0 -2 0Sample Output
20 11 13 10 1 4 10 3 5 10 10 10 0 -1 -2 0 0 0 Huge input, scanf is recommended.Hint
Hint問題鏈接:http://acm.hdu.edu.cn/showproblem.php?pid=1231
問題分析:動態規劃問題
對于最原始的最大子序列和問題有一個函數模板,大致思想如下:
for(int i=0;i<n;i++)//n為輸入序列的長度{if(cnt<0)cnt = 0;//cnt為記錄當前序列和的變量else cnt+=num[i];//num數組為輸入的序列if(cnt>maxx)maxx = cnt;//maxx用來保存最大序列和}AC:
#include<iostream> #include<stdio.h> using namespace std; int main() {int a[10005], n;while (cin >> n&&n){int u=1;for (int i = 0; i < n; i++) { scanf("%d", &a[i]); if (a[i] >= 0 && u)u = 0; }if (u) { printf("0 %d %d\n", a[0], a[n - 1]); continue; }int sum = -1000,s,e,maxn=-1000,l,r;for (int i = 0; i < n; i++){if (sum < 0){sum = a[i];l = a[i];r = a[i];}else sum += a[i];if (sum > maxn){maxn = sum;s = l;e = a[i];}}if (maxn < 0)printf("0 %d %d\n", s, e);else printf("%d %d %d\n", maxn, s, e);} }?
總結
以上是生活随笔為你收集整理的HDU1231(最大连续子序列)的全部內容,希望文章能夠幫你解決所遇到的問題。
 
                            
                        - 上一篇: 天运五行指的是什么 天运五行指的介绍
- 下一篇: 华硕无畏 Pro 15 2023 笔记本
