Cod sursa(job #604542)

Utilizator mihaipopa12Popa Mihai mihaipopa12 Data 23 iulie 2011 12:27:43
Problema PScNv Scor 90
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.22 kb
#include<stdio.h>
#include<vector>
#include<string>

#define maxN 250005
#define INF 1005

using namespace std;

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

int n,m,x,y,R,a,b,c,l,i,j;
int nod,nodvcn,Pos[maxN],H[maxN],L;
bool second; int D[maxN]; char line[30];

vector< pair<int,short int> >G[maxN];

inline void citire () {
	
	fscanf(f,"%d %d %d %d\n",&n,&m,&x,&y);
	
	for ( i = 1 ; i <= m ; ++i ){
		fgets(line+1,20,f); R = 0; second = 0; l = strlen(line+1);
		for ( j = 1 ; line[j] != '\n' && j <= l ; ++j ){
			if ( line[j] >= '0' && line[j] <= '9' )
				R = R * 10 + line[j] - '0';
			else{
				if ( line[j] == ' ' ){
					if ( second )
						b = R;
					else
						a = R,second = 1;
					R = 0;
				}
			}
		}
		c = R;
		G[a].push_back( make_pair(b,c) );
	}
}

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

inline void urca ( int x ){
	
	int p = x >> 1; int c = x;
	while ( p && D[H[p]] > D[H[c]] ){
		swap(H[p],H[c]); swap(Pos[H[p]],Pos[H[c]]);
		c = p; p = p >> 1;
	}
}

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

inline void push_heap ( int nod ){
	
	++L; H[L] = nod; Pos[nod] = L;
	urca(L);
}

inline int pop_heap () {
	int nod = H[1];
	H[1] = H[L]; Pos[H[1]] = Pos[H[L]];
	--L;
	coboara(1);
	return nod;
}

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

inline void dijkstra () {
	
	for ( i = 1 ; i <= n ; ++i ){
		D[i] = INF;
	}		
	D[x] = 0;
	push_heap(x); vector< pair<int,short int> >::iterator itt;
	
	while ( L ){
		nod = pop_heap(); if ( nod == y )	break;
		
		for ( itt = G[nod].begin() ; itt != G[nod].end() ; ++itt ){
			nodvcn = itt->first; c = itt->second;
			if ( D[nodvcn] > max(D[nod],c) ){
				D[nodvcn] = max(D[nod],c);
				if ( Pos[nodvcn] ){
					urca(Pos[nodvcn]);
				}
				else{
					push_heap(nodvcn);
				}
			}
		}
	}
	
	fprintf(g,"%d\n",D[y]);
}

int main () {
	
	citire();
	dijkstra();
	
	fclose(f);
	fclose(g);
	
	return 0;
}