Cod sursa(job #134237)

Utilizator vlad2179Popescu Vlad Alexandru vlad2179 Data 11 februarie 2008 00:28:31
Problema Energii Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.13 kb
#include <stdio.h>
#define INF 50000
FILE *f=fopen("energii.in","r"),*gg=fopen("energii.out","w");
unsigned long s1[5001],s2[5001],w,g,i,j;
struct gen{
	unsigned long v,c;
}ge[1001];
void swap(unsigned long a[], unsigned long b[]){
	unsigned long i;
	for(i=1;i<=w;i++) a[i]=b[i];

}
void date(){
	fscanf(f,"%ld %ld",&g,&w);
	for(i=1;i<=g;i++){
		fscanf(f,"%d %d",&ge[i].v,&ge[i].c);
	}
}

void init(){
	for(i=1;i<=w;i++){
		if(ge[1].v>=i) s1[i]=ge[1].c;
		else s1[i]=INF;
	}
}
void solve(){
	for(i=2;i<=g;i++){
		for(j=1;j<=w;j++){
			if(j<=ge[i].v && s1[j]!=INF){
				s2[j]=s1[j];
				if(s2[j]>ge[i].c){ s2[j]=ge[i].c; }
			}
			else if(s1[j]==INF){
				if(ge[i].v>=j) s2[j]=ge[i].c;
				else if(s1[j-ge[i].v]+ge[i].c<INF) s2[j]=s1[j-ge[i].v] + ge[i].c;
                                else s2[j]=INF;
			}
			else if(j>ge[i].v){ 	
				s2[j]=s1[j];
				if(s1[j-ge[i].v]+ge[i].c < s2[j]) s2[j]=s1[j-ge[i].v] + ge[i].c;

			}
		}swap(s1,s2);
	}
}
	inline void scrie(){
		if(s2[w]!=INF) fprintf(gg,"%ld", s2[w]);
	
		else fprintf(gg,"-1");
}
int main(){
	date();
	init();
	solve();
	scrie();
	return 0;
}