Cod sursa(job #2534749)

Utilizator petrisorvmyVamanu Petru Gabriel petrisorvmy Data 30 ianuarie 2020 21:52:02
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <set>
#include <vector>
#define NMAX 50010
#define inf 2047483646
using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int n, m,x,y,wh, dist[NMAX];
vector < pair<int,int> > G[NMAX];

void DJ(int start)
{
    for(int i = 1; i <= n; ++i)
        dist[i] = inf;
    dist[start] = 0;
    set <pair <int,int> > Q;
    Q.insert({0,start});
    while(!Q.empty())
    {
        int nod = (*Q.begin()).second;
        Q.erase(Q.begin());
        if(dist[nod] != inf)
            continue;
        for(auto it : G[nod])
        {
            int next = it.first;
            int cost = it.second;
            if(dist[nod] + cost < dist[next])
            {
                dist[next] = dist[nod] + cost;
                Q.insert({dist[next],next});
            }
        }
    }
}

int main()
{
    f >> n >> m;
    for(int i = 1; i <= m; ++i)
    {
        f >> x >> y >> wh;
        G[x].push_back({y,wh});
    }
    DJ(1);
    for(int i = 2; i <= n; ++i)
        if(dist[i] == inf)
            g << 0 << ' ';
        else
            g << dist[i] << ' ';
    f.close();
    g.close();
    return 0;
}