Cod sursa(job #1015977)

Utilizator lucianRRuscanu Lucian lucianR Data 25 octombrie 2013 15:18:05
Problema Sate Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.49 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define M_MAX 1000001
#define N_MAX 100001

using namespace std;
ifstream in("sate.in");
ofstream out("sate.out");

queue <int> q;
vector <int> graph[N_MAX];
int n, m, S, d[N_MAX], F;
bool found = false;

void BFS(int node)
{
    for(int i = 1; i <= n; i++)
        d[i] = -1;
    d[S] = 0;
    q.push(S);
    while(!q.empty() && found == 0)
    {
        int x = q.front();
        q.pop();
        for(int i = 0; i < graph[x].size(); i+=2)
        {
            //cout<<"i: "<<i<<" ";
            if(graph[x][i] == F) found = true;
            if(d[graph[x][i]] == -1)
            {
                //cout << x<<" "<<graph[x][i]<<" ";
                q.push(graph[x][i]);
                if(graph[x][i] > x) d[graph[x][i]] = d[x] + graph[x][i+1];
                else d[graph[x][i]] = d[x] - graph[x][i+1];
                //cout<< d[graph[x][i]]<< "     ";
            }
        }
        //cout<<endl;
    }
}

int main()
{
    in >> n >> m >> S >> F;
    int x, y, dd;
    for(int i = 0; i < m; i++)
    {
        in >> x >> y >> dd;
        graph[x].push_back(y);
        graph[y].push_back(x);
        graph[y].push_back(dd);
        graph[x].push_back(dd);
    }
    BFS(S);
    /*for(int i = 0; i <=n; i++){
    for(int j = 0; j < graph[i].size(); j++)
        cout << graph[i][j] << " ";
        cout<<endl;*/

    out<<d[F];
    in.close();
    out.close();
    return 0;
}