Cod sursa(job #1891098)

Utilizator miha1000Dica Mihai miha1000 Data 23 februarie 2017 18:53:45
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <queue>
#include <vector>
#include <fstream>
#define nmax 50005
#define inf 100000

using namespace std;

priority_queue<pair<int,int> > Q;

vector <pair< int, int > > G[nmax];
int dist[nmax];

void dijkstra(pair<int,int> start){
    Q.push(start);
    int nod,cost,i;
    while(!Q.empty()){
        nod=Q.top().second;
        cost=Q.top().first;
        Q.pop();
        for(i=0;i<G[nod].size();i++){
            if(dist[G[nod][i].second]>-cost+G[nod][i].first) {
                dist[G[nod][i].second]=-cost+G[nod][i].first;
                Q.push(make_pair(-dist[G[nod][i].second],G[nod][i].second));
            }
        }
    }
}

int main()
{
    ifstream f("dijkstra.in");
    ofstream g("dijkstra.out");
    int n,m,i,x,y,c;
    f >> n >> m;
    for(i=2;i<=n;i++){
        dist[i]=inf;
    }
    for(i=1;i<=m;i++){
        f >> x >> y >> c;
        G[x].push_back(make_pair(c,y));
    }
    dist[1]=0;
    pair <int,int > start;
    start=make_pair(0,1);
    dijkstra(start);
    for(i=2;i<=n;i++){
        if (dist[i]==inf) g << 0 << " ";
        else g << dist[i] << " ";
    }
}