Cod sursa(job #2163528)

Utilizator remus88Neatu Remus Mihai remus88 Data 12 martie 2018 18:40:17
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.49 kb
#include <fstream>
#include <vector>
#include <queue>
#define Nmax 50009
#define INF 999999999

using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

typedef pair <int,int> edge;
#define c first
#define x second

int n,m,d[Nmax],x,y,c;
vector <edge> G[Nmax];

struct cmp {

    bool operator()(const edge &a, const edge &b) const {

        return a.c > b.c;
    }
};

priority_queue <edge, vector<edge>, cmp> Q;

void ReadInput() {

    f>>n>>m;
    for (int i=1; i<=m; ++i) {

        f>>x>>y>>c;
        G[x].push_back(edge(c,y));

    }
}

void Dijkstra(int source) {

    for (int i=1; i<=n; ++i) d[i]=INF;
    d[source]=0;
    Q.push(edge(0,source));

    while (!Q.empty()) {

        edge aux=Q.top();
        Q.pop();
        int node=aux.x;
        int cost=aux.c;

        if (cost>d[node]) continue;

        for (auto it: G[node])
        {
            int x=it.x;
            int c=it.c;

            if (d[x]>d[node]+c || d[node]==INF) {

                d[x]=d[node]+c;
                Q.push(edge(d[x],x));
            }
        }
    }
}

void Solve() {


    Dijkstra(1);

//    for (int i=1; i<=n; ++i) {
//
//        for (auto j: G[i]) g<<'('<<j.c<<' '<<j.x<<") ";
//        g<<'\n';
//    }

    for (int i=2; i<=n; ++i)
    {
        if (d[i]==INF) g<<0<<' ';
        else g<<d[i]<<' ';
    }
}

int main() {

    ReadInput();
    Solve();

    f.close(); g.close();
    return 0;
}