题解:P16521 [GKS 2015 #E] Sums of Sums
题解:P16521 [GKS 2015 #E] Sums of Sums
简化题意
给那些懒得看题的人类。
给定正整数组
思路
为什么
想到用二分答案。设
其中
然后就可以用双指针计算
预处理
复杂度就是
代码
#include<bits/stdc++.h>
//Things will always be better, just let time play
using namespace std;
#define HACKILLER_FAST ios::sync_with_stdio(false),cin.tie(0)
#define int long long
#define rint register int
#define db double
#define pii pair<int,int>
#define vc vector
#define pb push_back
#define ls x<<1
#define rs x<<1|1
int T,n,q,a[200050],s[200050],ss[200050],sum,gcnt,gsum,ql,qr;
inline int count(int lmt){
int cnt = 0,cur = 0,r = 0;
for(int l = 1;l <= n;++l){
if(l > r){
r = l-1;
cur = 0;
}
while(r < n && cur+a[r+1] <= lmt){
++r;
cur+=a[r];
}
if(r >= l) cnt+=(r-l+1);
if(l <= r) cur-=a[l];
}
return cnt;
}
inline void work(int lmt){
gcnt = gsum = 0;
int cur = 0,r = 0;
for(int l = 1;l <= n;++l){
if(l > r){
r = l-1;
cur = 0;
}
while(r < n && cur+a[r+1] <= lmt){
++r;
cur+=a[r];
}
if(r >= l){
int len = r-l+1;
gcnt+=len;
gsum+=(ss[r]-ss[l-1]-len*s[l-1]);
}
if(l <= r) cur-=a[l];
}
}
inline int solve(int x){
if(x == 0) return 0;
int l = 1,r = sum,res = sum;
while(l <= r){
int mid = l+r>>1;
if(count(mid) >= x){
res = mid;
r = mid-1;
}
else l = mid+1;
}
work(res-1);
return gsum+res*(x-gcnt);
}
signed main(){
// freopen("data.in","r",stdin);
// freopen("task.out","w",stdout);
HACKILLER_FAST;
cin>>T;
for(int t = 1;t <= T;++t){
cin>>n>>q;
for(int i = 1;i <= n;++i) cin>>a[i];
s[0] = ss[0] = 0;
for(int i = 1;i <= n;++i) s[i] = s[i-1]+a[i];
for(int i = 1;i <= n;++i) ss[i] = ss[i-1]+s[i];
sum = s[n];
cout<<"Case #"<<t<<":"<<'\n';
while(q--){
cin>>ql>>qr;
cout<<solve(qr)-solve(ql-1)<<'\n';
}
}
return 0;
}
/*
Sometimes things go against your will
But true man never stops their steps
Toward the destiny that they fulfill
And gain the life that they want
Do what you feel is right to do
Don't try to interpret what the others may say
The more you try, the more you will be disappointed
Feel the warmness of others
Believe in the ones who you should believe in
No matter what they say
Do not question them
Follow their words
And the love song goes on
*/ //Wish for 99, Recall and watch the future, I will love her forever~