Cod sursa(job #1297325)

Utilizator stefanzzzStefan Popa stefanzzz Data 21 decembrie 2014 22:05:38
Problema Ferma Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.21 kb
#include <fstream>
#define MAXN 10005
#define INF 2000000000
using namespace std;
ifstream f("ferma.in");
ofstream g("ferma.out");

int n, k, v[MAXN], Sp[MAXN], pd[2][MAXN], maxpd[2][MAXN], act, ant = 1, val, mxi, sol;

inline int MAX(int a, int b){
	return (a > b)?a:b;
}

void compute_pd(int k);

int main(){
	int i;

	f >> n >> k;
	for(i = 1; i <= n; i++){
		f >> v[i];
		Sp[i] = Sp[i - 1] + v[i];
	}

	pd[act][0] = maxpd[act][0] = -INF;
	compute_pd(k);

	sol = maxpd[ant][n];

	pd[ant][0] = maxpd[ant][0] = -INF;
	for(i = 1; i <= n; i++){
		pd[ant][i] = Sp[i];
		maxpd[ant][i] = MAX(maxpd[ant][i - 1], pd[ant][i]);
	}
	//g << "\n\n\n";
	compute_pd(k - 1);
	for(i = n - 1; i >= 0; i--){
		if(Sp[n] - Sp[i] + maxpd[ant][i] > sol)
			sol = Sp[n] - Sp[i] + maxpd[ant][i];
	}

	if(sol < 0)
		g << "0\n";
	else
		g << sol << '\n';

	f.close();
	g.close();
	return 0;
}

void compute_pd(int k){
	int i;
	while(k--){
		mxi = 0;
		for(i = 1; i <= n; i++){
			pd[act][i] = Sp[i] - Sp[mxi] + maxpd[ant][mxi];
			maxpd[act][i] = MAX(maxpd[act][i - 1], pd[act][i]);
			val = maxpd[ant][i] - Sp[i];
			if(val > maxpd[ant][mxi] - Sp[mxi])
				mxi = i;
		}

		/*for(i = 1; i <= n; i++)
			g << pd[act][i] << ' ';
		g << "\n";*/
		swap(act, ant);
	}
}