Cod sursa(job #1723207)

Utilizator preda.andreiPreda Andrei preda.andrei Data 30 iunie 2016 00:31:37
Problema Sate Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.27 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>

using namespace std;

#define NMAX 30000

vector< pair<int, long long> > ad[NMAX + 1];
long long distante[NMAX + 1];

long long lungime(int x, int y);

int main()
{
    ifstream fin("sate.in");
    ofstream fout("sate.out");

    int n, m, fx, fy;
    fin >> n >> m >> fx >> fy;

    if(fx > fy)
        swap(fx, fy);

    while(m--){
        int x, y, c;
        fin >> x >> y >> c;
        ad[x].push_back(make_pair(y, c));
        ad[y].push_back(make_pair(x, c));
    }

    fout << lungime(fx, fy);
    return 0;
}

long long lungime(int x, int y){
    queue<int> q;

    q.push(x);
    distante[x] = 1;

    while(distante[y] == 0 && !q.empty()){
        int nod = q.front();
        q.pop();

        for(auto legatura : ad[nod]){
            int vecin = legatura.first;
            long long cost = legatura.second;

            if(distante[vecin] == 0){
                long long costNou = distante[nod];
                if(nod < vecin)
                    costNou += cost;
                else costNou -= cost;

                distante[vecin] = costNou;
                q.push(vecin);
            }
        }

    }

    return distante[y] - 1;
}