B. Light It Up (前缀和、模拟)

题目

预先做好一个所有偶数与前一个数差值和3以后奇数a[i]和前一个数差值的前缀和b[i](代表插入数后的情况),然后遍历插入到所有数后面的情况,假设插入到第i个数那么前i个数的贡献用a[i-1]表示,插入中间的贡献用lst[i]-lst[i-1]-1表示,后面的贡献用b[n+2]-b[i]表示,算出最大贡献即可。

Code:

#include<iostream>
using namespace std;
typedef long long ll;
const int Max = 1e6 + 5;
ll a[Max], b[Max], lst[Max];

int main()
{
    
    
	int n, m;cin >> n >> m;
	ll sum = 0;
	lst[1] = 0;lst[n + 2] = m;
	for (int i = 2;i <= n + 1;i++)
	{
    
    
		cin >> lst[i];
		a[i] = a[i - 1];
		b[i] = b[i - 1];
		if (i % 2 == 1)b[i] += lst[i] - lst[i - 1];
		else a[i] += lst[i] - lst[i - 1];
	}
	a[n + 2] = a[n + 1];
	b[n + 2] = b[n + 1];
	if ((n + 2) % 2 == 1)b[n + 2] += lst[n + 2] - lst[n + 1];
	else a[n + 2] += lst[n + 2] - lst[n + 1];
	ll ans = a[n + 2];
	for (int i = 2;i <= n + 2;i++)
	{
    
    
		if (i % 2 == 0) ans = max(ans, lst[i] - lst[i - 1] - 1 + b[n + 2] - b[i] + a[i - 2]);
		else ans = max(ans, lst[i] - lst[i - 1] - 1 + a[i - 1] + b[n + 2] - b[i]);
	}
	cout << ans << endl;
}

猜你喜欢

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