Submission #265526

#TimeUsernameProblemLanguageResultExecution timeMemory
265526square1001Split the sequence (APIO14_sequence)C++14
71 / 100
2036 ms83936 KiB
// APIO 2014 Problem 2 - Split the Sequence

#include <vector>
#include <iostream>
#include <algorithm>
using namespace std;
const long long inf = 1LL << 62;
int main() {
	// step #1. read input
	cin.tie(0);
	ios_base::sync_with_stdio(false);
	int N, K;
	cin >> N >> K; ++K;
	vector<int> A(N);
	for(int i = 0; i < N; ++i) {
		cin >> A[i];
	}
	// step #2. preparation for calculating the answer
	vector<int> S(N + 1);
	for(int i = 0; i < N; ++i) {
		S[i + 1] = S[i] + A[i];
	}
	// step #3. calculate the answer with dynamic programming
	vector<long long> dp(N + 1, inf);
	vector<vector<int> > pre(K + 1, vector<int>(N + 1, -1));
	dp[0] = 0;
	for(int i = 1; i <= K; ++i) {
		vector<long long> ndp(N + 1, inf);
		vector<int> st = { 0 };
		for(int j = 1; j <= N; ++j) {
			int l = 0, r = st.size();
			while(r - l > 2) {
				int lc = (l * 2 + r) / 3;
				int rc = (l + r * 2) / 3;
				long long la = dp[st[lc]] - 1LL * S[st[lc]] * S[j];
				long long lb = dp[st[rc]] - 1LL * S[st[rc]] * S[j];
				if(la > lb) l = lc;
				else r = rc;
			}
			for(int k = l; k < r; ++k) {
				long long x = dp[st[k]] - 1LL * S[st[k]] * S[j];
				if(ndp[j] > x) {
					ndp[j] = x;
					pre[i][j] = st[k];
				}
			}
			ndp[j] += 1LL * S[j] * S[j];
			while(st.size() >= 2) {
				int sz = st.size();
				__int128_t lc = __int128_t(dp[j] - dp[st[sz - 1]]) * (S[j] - S[st[sz - 2]]);
				__int128_t rc = __int128_t(dp[j] - dp[st[sz - 2]]) * (S[j] - S[st[sz - 1]]);
				if(lc <= rc) st.pop_back();
				else break;
			}
			st.push_back(j);
		}
		dp = ndp;
	}
	// step #4. print the answer
	cout << 1LL * S[N] * S[N] - dp[N] << endl;
	int pos = N;
	for(int i = K; i >= 2; --i) {
		cout << pre[i][pos] << (i != 2 ? ' ' : '\n');
		pos = pre[i][pos];
	}
	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...