Cod sursa(job #343363)

Utilizator marinaMarina Horlescu marina Data 25 august 2009 16:18:32
Problema Sate Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.31 kb
#include <stdio.h>
#define INPUT "sate.in"
#define OUTPUT "sate.out"

struct nod
{
	int vec;
	int cost;
	nod *leg;
};

int main()
{
	int n, m, x, y;
	
	freopen(INPUT, "r", stdin);
	freopen(OUTPUT, "w", stdout);
	
	scanf("%d %d %d %d", &n, &m, &x, &y); --x; --y;
	
	nod **graf = new nod*[n];
	int i;
	for(i = 0; i < n; ++i) graf[i] = NULL;
	

	for(i = 0; i < m; ++i)
	{
		int x, y, c;
		scanf("%d %d %d", &x, &y, &c); 
		--x; --y;
		nod *temp = new nod;
		temp -> vec = y;
		temp -> cost = c;
		temp -> leg = graf[x];
		graf[x] = temp;
		
		temp = new nod;
		temp -> vec = x;
		temp -> cost = c;
		temp -> leg = graf[y];
		graf[y] = temp;
	}
	
	int *queue = new int[n];
	int *dist = new int[n];
	int *t = new int[n];
	int *cost = new int[n];
	for(i = 0; i < n; ++i)
		dist[i] = -1;
	
	int in , sf;
	queue[in=sf=0] = x;
	dist[x] = 0;
	t[x] = -1;
	for(; in <= sf && dist[y] < 0; ++in)
	{
		int src = queue[in];
		nod *p;
		for(p = graf[src]; p; p = p -> leg)
			if(dist[p -> vec] < 0)
			{
				queue[++sf] = p -> vec;
				dist[p -> vec] = dist[src] + 1;
				t[p -> vec] = src;
				cost[p -> vec] = p -> cost;
			}
	}
	
	int d = 0;
	for(i = y; t[i] != -1; i = t[i])
		if(i < t[i]) d += cost[i];
		else d -= cost[i];
	if(d < 0) d = -d;
	printf("%d\n", d);
	return 0;
}