# Cod sursa(job #2346537)

Utilizator Data 17 februarie 2019 20:00:28 Ferma 100 cpp-64 done Arhiva de probleme 1.5 kb
``````#include <iostream>
#include <fstream>
#define Nmax 10005
#define Kmax 1005

using namespace std;

ifstream f("ferma.in");
ofstream g("ferma.out");

int n, k;
int a[Nmax], sum[Nmax];
int dp[Kmax][Nmax];

{
f >> n >> k;
for (int i = 1; i <= n; i++)
{
f >> a[i];
sum[i]=sum[i-1]+a[i];
}

}

void dinamica1()
{
for (int i = 1; i <= k; i++)
{
int max1 = dp[i-1][i-1] - sum[i-1];

for (int j = i; j <= n; j++)
{
dp[i][j] = max(dp[i][j-1], max1 + sum[j]);
max1 = max(max1, dp[i-1][j] - sum[j]);//pregatesc pentru j+1
}
}
}

void dinamica2()
{
for (int i = 2; i <= k; i++)
{
int max1 = dp[i-1][i-1] - sum[i];

for (int j = i; j <= n; j++)
{
dp[i][j] = max(dp[i][j-1], max1 + sum[j]);
max1 = max(max1, dp[i-1][j] - sum[j]);//pregatesc pentru j+1
}
}
}

void print()
{
for (int i = 1; i <= k; i++)
{
for (int j = 1; j <= n; j++)
cout << dp[i][j] << " " ;
cout << '\n';
}
cout << '\n';
}

void solve()
{
dinamica1();
int ans=dp[k][n];
dp[1][1]=sum[1];
for (int i = 2; i <= n; i++) dp[1][i] = max(dp[1][i-1], sum[i]);
dinamica2();
for (int i = 1; i <= n; i++) ans = max(ans, dp[k][i] + sum[n] - sum[i]);

//print();
//cout << ans;
g << ans;
}

int main()
{