Cod sursa(job #229634)

Utilizator Mishu91Andrei Misarca Mishu91 Data 10 decembrie 2008 21:39:54
Problema Sate Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.18 kb
#include <cstdio>
#include <queue>

using namespace std;

#define MAX_N 30005

typedef struct nod
{
    int nr, dst;
    nod *next;
}*list;

list V[MAX_N];
int N, M, X, Y;
int D[MAX_N];

void add(list &A, int nr, int dist)
{
    list aux = new nod;
    aux -> nr = nr;
    aux -> dst = dist;
    aux -> next = A;
    A = aux;
}

void citire()
{
    scanf("%d %d %d %d",&N, &M, &X, &Y);

    int x, y, z;
    for(int i = 1; i <= M; ++i)
    {
        scanf("%d %d %d",&x, &y, &z);
        if(x > y)
            x ^= y ^= x;
        add(V[x], y, z);
        add(V[y], x, -z);
    }
}

void solve()
{
    if(X == Y)
    {
        printf("0\n");
        return;
    }

    queue<int> Q;
    D[X] = -1;
    Q.push(X);

    while(!Q.empty())
    {
        int x = Q.front();
        Q.pop();

        for(list p = V[x]; p; p = p -> next)
        {
            if(D[p -> nr]) continue;
            D[p -> nr] = D[x] + p -> dst;
            if(p -> nr == Y)
            {
                printf("%d\n", D[Y]+1);
                return;
            }
            Q.push(p -> nr);
        }
    }
}

int main()
{
    freopen("sate.in","rt",stdin);
    freopen("sate.out","wt",stdout);

    citire();
    solve();
}