Cod sursa(job #2425664)

Utilizator dana.dascalescuDana Dascalescu dana.dascalescu Data 24 mai 2019 23:01:02
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.08 kb
#include <bits/stdc++.h>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int inf = 1e6;

int main()
{
    int N, M, A, B, C;
    fin>>N>>M;
    vector<vector<pair<int,int> > > G(N+1);
    for(int i = 1; i <= M; i++)
    {
        fin>>A>>B>>C;
        G[A].push_back({C,B});
    }
    vector<int> dist(N,inf);
    dist[1] = 0;

    set<pair<int,int> > Q;
    Q.insert({0,1});
    while(!Q.empty())
    {
        int current = (*Q.begin()).first;
        Q.erase(Q.begin());
        for(auto neighbour: G[current])
        {
            if(dist[current] + neighbour.second < dist[neighbour.first])
            {
                Q.erase(make_pair(dist[neighbour.first], neighbour.first));
                dist[neighbour.first] = dist[current] + neighbour.second;
                Q.insert({dist[neighbour.first],neighbour.first});
            }
        }
    }
    fin.close();
    for(int i = 2; i <= N; i++)
        if(dist[i] == inf) fout<<0<<' ';
            else fout<<dist[i]<<' ';
    fout.close();
    return 0;
}