Cod sursa(job #67582)

Utilizator sima_cotizoSima Cotizo sima_cotizo Data 25 iunie 2007 12:05:12
Problema Sate Scor 30
Compilator cpp Status done
Runda preONI 2007, Runda Finala, Clasa a 9-a si gimnaziu Marime 1.19 kb
#include <cstdio>

#define FIN "sate.in"
#define FOUT "sate.out"
#define MAX 30001

struct LISTA {
	long x,c; 
	LISTA *next;
} *A[MAX];
void add(long x, long y, long c) {
	LISTA *tmp = new LISTA;
	tmp -> x = y;
	tmp -> c = c;
	tmp -> next = A[x];
	A[x] = tmp;
}

long S, F, n, m, length;
bool visit[MAX];
LISTA *p, *u;

void push(long x, long c) {
	LISTA *tmp = new LISTA;
	tmp -> x = x;
	tmp -> c = c;
	tmp -> next = 0;
	u -> next = tmp;
	u = tmp;
}

void bf() {
	LISTA *vecin;
	
	p = new LISTA;
	p -> x = S; p -> c = 0;
	visit[S] = true;
	for (u=p; p; p=p->next)
		for (vecin=A[p->x]; vecin; vecin=vecin->next)
			if ( !visit[vecin->x] ) {
				push(vecin->x, p->c+vecin->c);
				visit[vecin->x] = true;
				if ( vecin->x == F ) {
					length = u->c;
					return;
				}
			}
}

int main() {
	long i, x, y, z;
	
	freopen(FIN, "r", stdin);
	scanf("%ld %ld %ld %ld", &n, &m, &S, &F);
	for (i=0; i<n; ++i) {
		scanf("%ld %ld %ld", &x, &y, &z);
		add(x,y,z);
		add(y,x,-z);
	}
	fclose(stdin);
	
	length = -1;
	if ( S>F ) {
		long aux = S;
		S = F; F = aux;
	}
	bf();
	
	freopen(FOUT, "w", stdout);
	printf("%ld\n", length);
	fclose(stdout);
	return 0;
}