题解:P11963 [GESP202503 六级] 环线
解析
在
遇到环,就先破环成链,为了减少分类讨论,我们将链复制一条,也就是要
于是再定义一个数组
代码
注意开long long。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll N = 4e5+1;
ll n, a[N], sum[N], b[N], ans=-2e18;
deque<ll> q;
// b[i]: [i-n+1, i-1]中最小的sum[i]
int main(){
cin>>n;
for(int i=1;i<=n;i++){cin>>a[i]; a[i+n]=a[i];}
for(int i=1;i<=n*2;i++) sum[i] = sum[i-1] + a[i];
for(int i=1;i<=n*2;i++){
while(!q.empty() && q.front() <= i-n) q.pop_front();
while(!q.empty() && sum[q.back()] >= sum[i]) q.pop_back();
q.push_back(i);
b[i] = sum[q.front()];
}
for(int i=1;i<=n*2;i++) ans = max(ans, sum[i] - b[i-1]);
cout << ans;
}