1358 - D. The Best Vacation (贪心+二分+前缀和)

题目

思路:贪心一下,要使拥抱次数最多必然是以每一个月的末尾为最后一天时,假设b(n-3) b(n-2) b(n-1) b(n) …c(1) c(2)… c(n)…a(n-4) a(n-3) 完后挪一个 b(n-2) b(n-1) b(n) …a(n-3) a(n-2) 当a(n-2)>b(n-3)时会使值增加,那么肯定继续挪到最后一个时a(n)最优。而a(n-2)<b(n-3)时我们往回挪使值增大,也挪到c(n)时最优。
现在可以知道我们只需枚举每一个最后的点即可,再前缀和记录预处理一下,求每个截至时贪心比较即可得出答案,细节见代码。

Code:

#include<iostream>
#include<string>
#include<map>
#include<algorithm>
#include<memory.h>
#include<cmath>
#define pii pair<int,int>
#define FAST ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
using namespace std;
typedef long long ll;
const int Max = 2e6 + 5;
int lst[Max];
ll sx[Max], s[Max];

int main()
{
    
    
	ll n, x;cin >> n >> x;
	for (int i = 1;i <= n;i++)
	{
    
    
		cin >> sx[i];sx[i + n] = sx[i];
		s[i+n]=s[i] = (sx[i] + 1) * sx[i] / 2;
	}
	for (int i = 1;i <= 2*n;i++)
	{
    
    
		sx[i] = sx[i-1] + sx[i];s[i] = s[i-1] + s[i];
	}
	ll ans = 0;
	for (int i = 1;i <= n * 2;i++)
	{
    
    
		if (sx[i] < x)continue;
		ll low = sx[i] - x;
		ll p = lower_bound(sx + 1, sx + 2 * n + 1, low) - sx;
		if (x == sx[i] - sx[p])ans = max(ans, s[i] - s[p]);
		else
		{
    
    
			ll dnum = low - sx[p - 1];
			ans = max(ans, s[i] - s[p - 1] - (dnum + 1)*dnum / 2);
		}
	}
	cout << ans << endl;
}

猜你喜欢

转载自blog.csdn.net/asbbv/article/details/112759310