問題:
N個整陣列成的回圈序列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
輸出回圈陣列的最大子段和
#include<iostream>
#include<vector>
using namespace std;
vector <int> a;
vector <int> b;
int main()
{
int n;
cin>>n;
a.resize(n);
int i,j;
for(i=0;i<n;i++)
cin>>a[i];
b.resize(n);
b=a;
a.insert(a.end(),b.begin(),b.end());//將原先的陣列首尾連接,構成一個兩倍的陣列
int t=0;
int t1=0,t2=0;
long long int sum=0;
long long int max=0;
for(i=0;i<2*n;i++)
{
sum+=a[i];
t++;
if(t>n) //t表示已經有幾個數字相加,當t>n是應做處理
{
//cout<<"tiaole"<<"i"<<endl;
//cout<<"xunhuan"<<t1<<" "<<t<<endl;
sum-=a[t1];
t--;
t1++;
while(a[t1]<=0)
{
sum-=a[t1];
t--;
t1++;
}
}
if(max<=sum)
{
max=sum;
t2=i;
}
// cout<<"sum="<<sum<<endl;
if(sum<=0)
{
sum=0;
t=0;
t1=i+1;
}
// cout<<"sum="<<sum<<" max="<<max<<" t="<<t<<endl;
}
cout<<max<<endl;
return 0;
}
/*6
2 -1 -1 2 -1 2*/
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/67680.html
標籤:基礎類
上一篇:資料庫
