简单斜率优化,这里保存代码。

const int N = 1e5 + 10, M = 1e4 + 5;

inline ll Read() {
	ll x = 0, f = 1;
	char c = getchar();
	while (c != '-' && (c < '0' || c > '9')) c = getchar();
	if (c == '-') f = -f, c = getchar();
	while (c >= '0' && c <= '9') x = (x << 3) + (x << 1) + c - '0', c = getchar();
	return x * f;
}

namespace Main {
	int n;
	ll a[N], s[N], f[N];
	int cnt[M];
	vector <int> q[M];
	
	long double slope (int x, int y) {
		return (long double)(f[x - 1] - f[y - 1]
			+ a[x] * s[x] * s[x] - a[y] * s[y] * s[y]
			- 2 * a[x] * s[x] + 2 * a[y] * s[y]) / (s[x] - s[y]);
	}
	
	int main () {
		n = Read();
		for (int i = 1; i <= n; i++) a[i] = Read();
		for (int i = 1; i <= n; i++) s[i] = ++cnt[a[i]];
		for (int i = 1; i <= n; i++) {
			for (; q[a[i]].size() > 1 && slope(*(q[a[i]].end() - 2), i) >= slope(*(q[a[i]].end() - 2), *(q[a[i]].end() - 1)); q[a[i]].pop_back());
			q[a[i]].push_back(i);
			for (; q[a[i]].size() > 1 && (f[*(q[a[i]].end() - 1) - 1] + a[i] * (s[i] - s[*(q[a[i]].end() - 1)] + 1) * (s[i] - s[*(q[a[i]].end() - 1)] + 1)) <= (f[*(q[a[i]].end() - 2) - 1] + a[i] * (s[i] - s[*(q[a[i]].end() - 2)] + 1) * (s[i] - s[*(q[a[i]].end() - 2)] + 1)); q[a[i]].pop_back());
			int j = q[a[i]].back();
			f[i] = f[j - 1] + a[i] * (s[i] - s[j] + 1) * (s[i] - s[j] + 1);
		}
		printf ("%lld\n", f[n]);
		return 0;
	}
}

int main () {
//	freopen(".in", "r", stdin);
//	freopen(".out", "w", stdout);
	Main::main();
	return 0;
}
EOF

评论

暂无评论

发表评论

可以用@mike来提到mike这个用户,mike会被高亮显示。如果你真的想打“@”这个字符,请用“@@”。

博客信息

作者
Jayun
时间
2023-10-18 09:46:30
博客类型