Submission #384045

#TimeUsernameProblemLanguageResultExecution timeMemory
384045Drew_Split the sequence (APIO14_sequence)C++14
50 / 100
2088 ms4968 KiB
#include <iostream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

#pragma GCC target ("avx2")
#pragma GCC optimize ("Ofast")
#pragma GCC optimize ("unroll-loops")

#define ll long long
#define pb push_back
#define ii pair<int, int>
#define f1 first
#define s2 second

const int MAX = 1e5 + 7;

int n;
//ll ar[MAX];
ll pfx[MAX];
ll dp[201][MAX];
int par[201][MAX];
inline void rc(int k, int l, int r, int optL, int optR)
{
	queue<pair<ii, ii>> q;
	q.push({{l, r}, {optL, optR}});

	while (!q.empty())
	{
		l = q.front().f1.f1;
		r = q.front().f1.s2;
		optL = q.front().s2.f1;
		optR = q.front().s2.s2;
		q.pop();

		if (l > r)
			continue;

		int mid = (l + r) / 2;
		ll optVal = -1, optIdx = -1;

		for (int i = optL; i <= mid && i <= optR; ++i)
		{
			//segment [i, n], cut at mid
			ll v = dp[k-1][i-1]	+ (pfx[mid] - pfx[i-1]) * (pfx[n] - pfx[mid]);
			if (v > optVal)
			{
				optVal = v;
				optIdx = i;
			}
		}

		dp[k][mid] = optVal;
		par[k][mid] = optIdx;

		q.push({{l, mid-1}, {optL, optR}});
		q.push({{mid+1, r}, {optL, optR}});
	}

	/*
	if (l > r)
		return;

	int mid = (l + r) / 2;
	ll optVal = -1, optIdx = -1;

	for (int i = optL; i <= mid && i <= optR; ++i)
	{
		//segment [i, n], cut at mid
		ll v = dp[k-1][i-1]	+ (pfx[mid] - pfx[i-1]) * (pfx[n] - pfx[mid]);
		if (v > optVal)
		{
			optVal = v;
			optIdx = i;
		}
	}

	dp[k][mid] = optVal;
	par[k][mid] = optIdx;

	rc(k, l, mid-1, optL, optR);
	rc(k, mid+1, r, optL, optR);
	*/
}

int main()
{
	ios :: sync_with_stdio(0);
	cin.tie(0);
	cout.tie(0);

	int k;
	cin >> n >> k;

	for (int i = 1; i <= n; ++i)
		cin >> pfx[i], pfx[i] += pfx[i-1];

	for (int i = 1; i <= n; ++i)
		dp[0][i] = 0;

	for (int i = 1; i <= k; ++i)
		rc(i, i, n, i, n);



	ll res = -1, idx = -1;
	for (int i = 1; i <= n; ++i)
	{
		if (res < dp[k][i])
			res = dp[k][i], idx = i;
	}
	cout << res << '\n';

	vector<int> cut;
	cut.pb(idx);

	for (int j = k-1; j >= 1; --j)
	{
		res -= (pfx[idx] - pfx[par[j+1][idx] - 1]) * (pfx[n] - pfx[idx]);
		
		for (int i = par[j+1][idx] - 1; i >= 1; --i)
		{
			if (dp[j][i] == res)
			{
				idx = i;
				break;
			}
		}
		cut.pb(idx);
	}

	for (int i = k-1; i >= 0; --i)
	{
		cout << cut[i];
		if (i) cout << " ";
	}
	cout << '\n';

	return 0;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...