Cod sursa(job #554042)

Utilizator feelshiftFeelshift feelshift Data 14 martie 2011 15:41:44
Problema Sate Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 1.37 kb
// http://infoarena.ro/problema/sate
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

#define maxSize 30001
#define location first
#define cost second

ifstream in("sate.in");
ofstream out("sate.out");

int nodes,destination;
int dist[maxSize];
vector< pair<int,int> > graph[maxSize];

int bellmanFord(int source);

int main() {
    int edges,source;

    in >> nodes >> edges;
    in >> source >> destination;

    int from,to,cost;
    for(int i=1;i<=edges;i++) {
        in >> from >> to >> cost;

        graph[from].push_back(make_pair(to,cost));
        graph[to].push_back(make_pair(from,-cost));
    }

    out << bellmanFord(source);

    in.close();
    out.close();

    return (0);
}

int bellmanFord(int source) {
    dist[source] = 0;

    int node;
    vector< pair<int,int> >::iterator it,end;

    queue<int> myQueue;
    myQueue.push(source);

    while(!myQueue.empty()) {
        node = myQueue.front();
        myQueue.pop();

        end = graph[node].end();
        for(it=graph[node].begin();it!=end;++it)
            if(!dist[it->location]) {
                dist[it->location] = dist[node] + it->cost;
                myQueue.push(it->location);

                if(it->location == destination)
                    return dist[it->location];
            }
    }

    return (0);
}