Cod sursa(job #642489)

Utilizator mihaipopa12Popa Mihai mihaipopa12 Data 1 decembrie 2011 15:29:26
Problema Pitici Scor 50
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.93 kb
#include<stdio.h>
#include<queue>

#define maxn 1022
#define mp make_pair
#define pss pair<short int,short int>
#define pb push_back

using namespace std;

FILE*f=fopen("pitici.in","r");
FILE*g=fopen("pitici.out","w");

int n,m,k,i,x,y,c,nod,sol[maxn];
vector< pss >G[maxn];
int H[maxn][maxn];
queue<int>Q; int Gr[maxn];

inline void swap ( int &a , int &b ){
	int aux = a; a = b; b = aux;
}

inline void urca ( int h , int poz ){
	
	while ( poz > 1 && H[h][poz>>1] < H[h][poz] ){
		swap(H[h][poz>>1],H[h][poz]);
		poz >>= 1;
	}
}

inline void coboara ( int h , int x ){
	int y = 0;
	
	while ( x != y ){
		y = x;
		if ( (y<<1) <= H[h][0] && H[h][y<<1] > H[h][x] ){
			x = y<<1;
		}
		if ( (y<<1)+1 <= H[h][0] && H[h][(y<<1)+1] > H[h][x] ){
			x = (y<<1)+1;
		}
		swap(H[h][x],H[h][y]);
	}
}

inline void add_heap ( int h , int val ){
	H[h][++H[h][0]] = val; urca(h,H[h][0]);
}

inline void erase_first ( int h ){
	swap(H[h][1],H[h][H[h][0]]); H[h][H[h][0]] = 0; --H[h][0]; coboara(h,1);
}

int main () {
	
	fscanf(f,"%d %d %d",&n,&m,&k);
	
	for ( i = 1 ; i <= m ; ++i ){
		fscanf(f,"%d %d %d",&x,&y,&c);
		G[x].pb(mp(y,c)); ++Gr[y];
	}
	
	add_heap(1,0); Q.push(1);
	
	while ( !Q.empty() ){
		nod = Q.front(); Q.pop();
		if ( nod == n )	break ;
		
		for ( vector< pss >::iterator itt = G[nod].begin() ; itt != G[nod].end() ; ++itt ){
			--Gr[itt->first];
			if ( !Gr[itt->first] ){
				Q.push(itt->first);
			}
		}
		
		for ( i = 1 ; i <= H[nod][0] ; ++i ){
			for ( vector< pss >::iterator itt = G[nod].begin() ; itt != G[nod].end() ; ++itt ){
				add_heap(itt->first,H[nod][i]+itt->second);
				if ( H[itt->first][0] == k + 1 ){
					erase_first(itt->first);
				}
			}
		}
	}
	
	for ( i = k; i >= 1 ; --i ){
		sol[i] = H[n][1];
		erase_first(n);
	}
	
	for ( i = 1 ; i <= k ; ++i ){
		fprintf(g,"%d ",sol[i]);
	}
	fprintf(g,"\n");
	
	fclose(f);
	fclose(g);
	
	return 0;
}