Codeforces Round #645 (Div. 2) D. The Best Vacation(二分+前缀和)
You've been in love with Coronavirus-chan for a long time, but you didn't know where she lived until now. And just now you found out that she lives in a faraway place called Naha.
You immediately decided to take a vacation and visit Coronavirus-chan. Your vacation lasts exactly xx days and that's the exact number of days you will spend visiting your friend. You will spend exactly xx consecutive (successive) days visiting Coronavirus-chan.
They use a very unusual calendar in Naha: there are nn months in a year, ii -th month lasts exactly didi days. Days in the ii -th month are numbered from 11 to didi . There are no leap years in Naha.
The mood of Coronavirus-chan (and, accordingly, her desire to hug you) depends on the number of the day in a month. In particular, you get jj hugs if you visit Coronavirus-chan on the jj -th day of the month.
You know about this feature of your friend and want to plan your trip to get as many hugs as possible (and then maybe you can win the heart of Coronavirus-chan).
Please note that your trip should not necessarily begin and end in the same year.
The first line of input contains two integers nn and xx (1≤n≤2⋅1051≤n≤2⋅105 ) — the number of months in the year and the number of days you can spend with your friend.
The second line contains nn integers d1,d2,…,dnd1,d2,…,dn , didi is the number of days in the ii -th month (1≤di≤1061≤di≤106 ).
It is guaranteed that 1≤x≤d1+d2+…+dn1≤x≤d1+d2+…+dn .
Print one integer — the maximum number of hugs that you can get from Coronavirus-chan during the best vacation in your life.
3 2 1 3 1
5
3 6 3 3 3
12
5 6 4 2 3 1 3
15
首先可以知道所选的这段日期的结尾一定是月末。因为如果x小于等于最大的d[i]的话,肯定选择i这个月的末尾这连续x天;
如果x大于最大的d[i]的话(注意这里不一定是以最大的月的月末为右端点
考虑 1 1 1 4 2这组)然后就不知道怎么证明了选取的这段日期一定至少覆盖到两个月份。如果右端点不是月末的话,假设左端点对应的日期大于右端点对应的日期,那么整体往左移动区间就能使得答案增加;同理假设左端点对应的日期小于右端点对应的日期可以整体往右移动。最后会使得右端点靠到某个月的月末。
所以要做的就是枚举每个月的月末,通过之前预处理出的前缀和找到左端点所在的月,根据x求出答案更新即可。
#include <bits/stdc++.h> using namespace std; long long d[400005]; long long sum[400005]; long long ssum[400005]; long long ans=0; long long n,x;//x一定要开long long 因为是d的和 int check(long long mid,long long k) { if(sum[k]-sum[mid]>=x) return 0; else { if(sum[k]-sum[mid-1]>=x) return 1; else return 2; } } int main() { cin>>n>>x; int i; for(i=1;i<=n;i++) { scanf("%lld",&d[i]); d[i+n]=d[i]; } for(i=1;i<=2*n;i++) { sum[i]=sum[i-1]+d[i]; ssum[i]=ssum[i-1]+(1+d[i])*d[i]/2; } for(i=n+1;i<=2*n;i++) { long long l=1,r=i,mid,pos; while(1) { mid=(l+r)/2; int judge=check(mid,i); if(judge==2) r=mid; else if(judge==0) l=mid+1; else { pos=mid; break; } } if(pos==i)//在同一个月 { ans=max(ans,x*d[i]-(long long)x*(x-1)/2*1); } else { long long temp=ssum[i]-ssum[pos]; long long xx=x-(sum[i]-sum[pos]); temp+=xx*d[pos]-xx*(xx-1)/2; ans=max(ans,temp); } } cout<<ans<<endl; return 0; }