Cod sursa(job #624767)

Utilizator andra23Laura Draghici andra23 Data 22 octombrie 2011 19:13:15
Problema Energii Scor 5
Compilator cpp Status done
Runda Arhiva de probleme Marime 0.79 kb
#include<iostream>
#include<fstream>

using namespace std;

const int MAXN = 1005;
const int MAXW = 5005;
const int MAXSUM = 20000000;
int c[MAXW], d[MAXW], e[MAXN], cost[MAXN];

int main() {
	ifstream f("energii.in");
	ofstream g("energii.out");

	int gen, w;
	f >> gen >> w;

	for (int i = 1; i <= gen; i++) {
		f >> e[i] >> cost[i];
	}
	
	for (int i = 0; i <= w; i++) {
		c[i] = MAXSUM;
		d[i] = MAXSUM;
	}
	c[0] = 0;
	c[e[1]] = cost[1];

	for (int i = 2; i <= gen; i++) {
		for (int j = 0; j <= w; j++) {
			if (c[j] < MAXSUM) {
				d[j] = min(d[j], c[j]);
				if (j+e[i] <= w) {
					d[j+e[i]] = min(d[j+e[i]], c[j]+cost[i]);
				}
			}
		}
		for (int j = 0; j <= w; j++) {
			c[j] = d[j];
			d[j] = MAXSUM;
		}
	}

	if (c[w] < MAXSUM) {
		g << c[w] << '\n';
	} else {
		g << "-1" << '\n';
	}

	return 0;
}