1. 程式人生 > 實用技巧 >codeforces 1175D. Array Splitting

codeforces 1175D. Array Splitting

cf傳送門
vjudge傳送門


首先,人人都能想到一個很顯然的dp做法:令\(dp[i][j]\)表示前\(i\)個數分成\(j\)段的最大劃分價值,於是有\(dp[i][j] = max \{dp[i-1][j], dp[i-1][j-1] \} + a[i]*j\).
但這樣\(O(n^2)\)妥妥的不能優化,沒了。


然後我不知咋的就想到了這麼個思路:
如果\(k=1\),那麼答案就是所有\(a[i]\)之和。
接下來假如在\(i\)出劃分成新的兩段,對答案的貢獻就是\(\sum_{j=i}^{n}a[j]\),即字尾和\(sum'[i]\)
又因為每一個元素只能出現在兩個連續子序列裡,那麼只要選前\(k-1\)

大的字尾和就好啦。


需要注意的是\(sum'[1]\)一定要選,因此除了\(sum'[1]\)要再選\(k-1\)個。

#include<cstdio>
#include<algorithm>
#include<cctype>
using namespace std;
#define enter puts("") 
#define space putchar(' ')
#define In inline
typedef long long ll;
const int maxn = 3e5 + 5;
In ll read()
{
	ll ans = 0;
	char ch = getchar(), las = ' ';
	while(!isdigit(ch)) las = ch, ch = getchar();
	while(isdigit(ch)) ans = (ans << 1) + (ans << 3) + ch - '0', ch = getchar();
	if(las == '-') ans = -ans;
	return ans;
}
In void write(ll x)
{
	if(x < 0) x = -x, putchar('-');
	if(x >= 10) write(x / 10);
	putchar(x % 10 + '0');
}

int n, K, a[maxn];
ll sum[maxn], ans = 0;

int main()
{
//	MYFILE();
	n = read(), K = read();
	for(int i = 1; i <= n; ++i) a[i] = read();
	if(n == 1) {write(a[1]), enter; return 0;}
	for(int i = n; i > 1; --i)
	{
		sum[i] = sum[i + 1] + a[i];
		ans += a[i];
	}
	ans += a[1];
	sort(sum + 2, sum + n + 1, [&](ll a, ll b) {return a > b;});
	for(int i = 2; i <= K; ++i) ans += sum[i];
	write(ans), enter;
	return 0;
}