Cod sursa(job #480257)

Utilizator tamas_iuliaTamas Iulia tamas_iulia Data 27 august 2010 11:22:23
Problema Zebughil Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.49 kb
#include <stdio.h>
#include <queue>
#define Nmax 18
#define mp make_pair
#define wh first
#define cam second

using namespace std;

queue< pair<int,int> > Q;
queue< int > Qg;
int din[1<<Nmax],mcam[1<<Nmax];
int v[Nmax];
int n,G;

inline int Maxim(int x,int y){ return x>y ? x:y; }

void work(){
	int i,j,k,g; pair<int,int> q;
	while( ! Q.empty() ) Q.pop(),Qg.pop();
	Q.push(mp(0,1)); Qg.push(G); 
	
	for(i=0;i<(1<<n);++i) for(j=1;j<=n;++j) din[i]=-1,mcam[i]=n+1;
	din[0]=G; mcam[0]=1;
	
	while( ! Q.empty() ){
		q=Q.front(); g=Qg.front();
		if( q.wh == (1<<n)-1 ) return;
		Q.pop(); Qg.pop();
		for(k=0;k<n;++k)
			if((q.wh & (1<<k)) == 0 )
				if( g >= v[k+1] )
					if( mcam[q.wh|(1<<k)]>q.cam || 
						(mcam[q.wh|(1<<k)]==q.cam &&din[q.wh|(1<<k)] < din[q.wh]-v[k+1]) ){
						
						din[q.wh|(1<<k)] = din[q.wh]-v[k+1];
						mcam[q.wh|(1<<k)]= q.cam;
						Q.push(mp(q.wh|(1<<k),q.cam)); Qg.push(din[q.wh]-v[k+1]);
					} else;
				else if( mcam[q.wh|(1<<k)]>q.cam+1 || 
						(mcam[q.wh|(1<<k)]==q.cam+1 &&din[q.wh|(1<<k)]< G-v[k+1]) ){
						
						din[q.wh|(1<<k)] = G-v[k+1];
						mcam[q.wh|(1<<k)]= q.cam+1;
						Q.push(mp(q.wh|(1<<k),q.cam+1)); Qg.push(G-v[k+1]);
					}
	}
}

int main(){
	int i,t;
	freopen("zebughil.in","r",stdin);
	freopen("zebughil.out","w",stdout);
	for(t=1;t<=3;++t){
		scanf("%d%d",&n,&G);
		for(i=1;i<=n;++i) scanf("%d",&v[i]);
		
		work();
	
		printf("%d\n",mcam[(1<<n)-1]);
	}
	
	fclose(stdin); fclose(stdout);
	return 0;
}