標籤:n+1 開始 元素 set 最大和 gray scan ring input
個整數組成的迴圈序列a[1],a[2],a[3],…,a[n],求該序列如a[i]+a[i+1]+…+a[j]的連續的子段和的最大值(迴圈序列是指n個數圍成一個圈,因此需要考慮a[n-1],a[n],a[1],a[2]這樣的序列)。當所給的整數均為負數時和為0。例如:-2,11,-4,13,-5,-2,和最大的子段為:11,-4,13。和為20。 Input
第1行:整數序列的長度N(2 <= N <= 50000)第2 - N+1行:N個整數 (-10^9 <= S[i] <= 10^9)
Output
輸出迴圈數組的最大子段和。
Input樣本
6-211-413-5-2
Output樣本
20
第一次以每個元素作為起點求所有可能,遍曆一遍,複雜度n*n,逾時。後來看了網上的解法,複雜度n。
最大欄位和迴圈序列有兩種情況,一是中間某部分和最大,無跨越情況,如 -1 2 3 5 -2,最大和是10,另一種情況是由首位兩段組成如 3 5 -100 -200 1,最大和為9。
第一種情況易解,第二種情況只需求出中間部分的最小值,然後用數組所有元素和減去即可。
正解:
#include <iostream>#include <cstdio>#include <string>#include <cstring>#include <fstream>#include <algorithm>#include <cmath>#include <queue>#include <stack>#include <vector>#include <map>#include <set>#include <iomanip>using namespace std;#define maxn 1000005#define MOD 1000000007#define mem(a , b) memset(a , b , sizeof(a))#define LL long long#define INF 1000000000int a[maxn] ;int n;int main(){ while(scanf("%d" , &n) != EOF) { int flag = 0; LL sum = 0 , all = 0; for(int i = 0; i < n ; i ++) { scanf("%d" , &a[i]); all += a[i]; } LL maxx = 0; for(int i = 0 ; i < n ; i ++) { sum += a[i]; if(sum > maxx) maxx = sum; if(sum < 0) sum = 0; } for(int i = 0 ; i < n ; i ++) a[i] = -a[i]; sum = 0 ; LL maxx2 = 0; for(int i = 0 ; i < n ; i ++) { sum += a[i]; if(sum > maxx2) maxx2 = sum; if(sum < 0) sum = 0; } printf("%lld\n" ,max(maxx , maxx2 + all)); } return 0;}
錯解:
#include<iostream>#include<stdio.h>#include<cstring>#include<cstdlib>#include<algorithm>#define LL long longusing namespace std;/*sum[j+1] = d[j+1] + sum[j]>0?sum[j]:0;有一個n2複雜度的方法。__數組開太大了。。*/#define MAXN 50001LL a[MAXN];//LL dp[MAXN];dp[i] 從i開始的最大值LL n,ans=-MAXN,temp,result;//temp記錄sum[j],ans記錄結果int main(){ scanf("%lld",&n); for(LL i=0;i<n;i++) { scanf("%lld",&a[i]); } for(LL i=0;i<n;i++) { temp = a[i]; for(LL j=i+1,cnt=1; cnt<n; cnt++,j=(j+1)%n) { temp = a[j] + (temp>0?temp:0); //cout<<a[j]<<endl; ans = max(ans,temp); } result = max(ans,result); ans = -MAXN; //cout<<endl<<endl<<dp[i]<<endl<<endl; } //<<endl; printf("%lld\n",result); return 0;}
1050 迴圈數組最大子段和