跳到正文

剪贴板

剪贴板 r9nspllp

原文
剪贴板信息

剪贴板信息

收录
更新
C++
#include <cstdio>
#include <algorithm>

using namespace std;

namespace fast_read{
	char buf[1000005], *s = buf, *t = buf, ch;
	#define gc() s == t && (t = (s = buf) + fread(buf, 1, 1000000, stdin), s == t) ? EOF : *s ++
	template <typename T>
	inline void read(T &x)
	{
		x = 0, ch = gc();
		while(ch < '0' || ch > '9') ch = gc();
		while('0' <= ch && ch <= '9') x = x * 10 + ch - 48, ch = gc();
	}
};
using fast_read::read;

typedef long long LL;

const int N = 1e6 + 5;

int n, c, a[N], p[N], s;
struct node{
	int a, b;
	LL f, g, add, xadd, cov;
}t[N * 4];

#define Add(u, d, xd) t[u].f += d + p[t[u].b] * xd, t[u].g += d + p[t[u].a] * xd, t[u].add += d, t[u].xadd += xd
#define Cover(u, d) t[u].f = t[u].g = t[u].cov = d, t[u].add = t[u].xadd = 0
inline void build(int u, int a, int b)
{
	t[u].a = a, t[u].b = b, t[u].cov = -1;
	if(a != b)
	{
		int mid = a + b >> 1;
		build(u << 1, a, mid), build(u << 1 | 1, mid + 1, b);
	}
}
inline void modify(int u, int x, int y, LL d, LL xd)
{
	if(x <= t[u].a && t[u].b <= y)
	{
		Add(u, d, xd);
		return ;
	}
	int ls = u << 1, rs = ls | 1;
	if(t[u].cov != -1) Cover(ls, t[u].cov), Cover(rs, t[u].cov), t[u].cov = -1;
	if(t[u].add || t[u].xadd) Add(ls, t[u].add, t[u].xadd), Add(rs, t[u].add, t[u].xadd), t[u].add = t[u].xadd = 0;
	if(t[ls].b >= x) modify(ls, x, y, d, xd);
	if(t[rs].a <= y) modify(rs, x, y, d, xd);
	t[u].f = max(t[ls].f, t[rs].f);
	t[u].g = min(t[ls].g, t[rs].g);
}
inline void binary(int u, int x, LL d)
{
	if(t[u].b <= x && t[u].g > d)
	{
		Cover(u, d);
		return ;
	}
	if(t[u].a == t[u].b) return ;
	int ls = u << 1, rs = ls | 1;
	if(t[u].cov != -1) Cover(ls, t[u].cov), Cover(rs, t[u].cov), t[u].cov = -1;
	if(t[u].add || t[u].xadd) Add(ls, t[u].add, t[u].xadd), Add(rs, t[u].add, t[u].xadd), t[u].add = t[u].xadd = 0;
	if(t[rs].a <= x && (t[rs].b >= x || t[rs].f > d)) binary(rs, x, d);
	if(t[ls].b >= x || t[ls].f > d) binary(ls, x, d);
	t[u].f = max(t[ls].f, t[rs].f);
	t[u].g = min(t[ls].g, t[rs].g);
}
inline LL query(int x)
{
	int u = 1, ls, rs;
	while(t[u].a != t[u].b)
	{
		ls = u << 1, rs = ls | 1;
		if(t[u].cov != -1) Cover(ls, t[u].cov), Cover(rs, t[u].cov), t[u].cov = -1;
		if(t[u].add || t[u].xadd) Add(ls, t[u].add, t[u].xadd), Add(rs, t[u].add, t[u].xadd), t[u].add = t[u].xadd = 0;
		if(t[ls].b >= x) u = ls;
		else u = rs;
	}
	return t[u].f;
}

int main()
{
	read(n), read(c);
	for(int i = 1; i <= n; i ++ ) read(a[i]), p[i] = a[i];
	sort(p + 1, p + n + 1);
	s = unique(p + 1, p + n + 1) - p - 1;
	build(1, 1, s);
	for(int i = 1; i <= n; i ++ )
	{
		int t = lower_bound(p + 1, p + s + 1, a[i]) - p;
		if(t > 1) modify(1, 1, t - 1, c, 0);
		if(t < n) modify(1, t, s, -p[t], 1);
		if(t > 1) binary(1, t - 1, query(t));
//		printf("#%d %d\n", i, t);
//		for(int i = 1; i <= s; i ++ ) printf("%d ", query(1, i));
//		puts("");
	}
	printf("%lld\n", query(1));
	return 0;
}