Cod sursa(job #2513860)

Utilizator Data 23 decembrie 2019 22:27:55 Ferma 20 cpp-64 done Arhiva de probleme 1.24 kb
``````#include <iostream>
#include <fstream>
#define MAXN 10005
#define inf 1000000000
#define MAXK 1024
using namespace std;

ifstream fin("ferma.in");
ofstream fout("ferma.out");

int n, K, prod[MAXN], s[MAXN], dp[MAXK][MAXN], res;

void citire() {
fin >> n >> K;
for(int i = 1; i <= n; i++)
fin >> prod[i];
}

void solve() {
s[1] = prod[1];
for(int i = 2; i<= n; i++)
s[i] = s[i-1]+prod[i];

for(int i = 1; i <= K; i++) {
dp[i][i] = s[i];
int maxim = dp[i-1][i]-s[i];
for(int j = i+1; j <= n; j++) {
dp[i][j] = max(dp[i][j-1], maxim+s[j]);
maxim = max(maxim, dp[i-1][j]-s[j]);
}
}

for(int j = K; j <= n; j++)
res = max(res, dp[K][j]);

for(int i = 1; i <= n; i++)
dp[1][i] = max(dp[1][i-1], s[i]);

for(int i = 1; i <= K; i++) {
dp[i][i] = s[i];
int maxim = dp[i-1][i]-s[i];
for(int j = i+1; j <= n; j++) {
dp[i][j] = max(dp[i][j-1], maxim+s[j]);
maxim = max(maxim, dp[i-1][j]-s[j]);
}
}

for(int j = K; j <= n; j++)
res = max(res, dp[K][j]+s[n]-s[j]);
}

int main() {
citire();
solve();
fout << res;
}
``````