Cod sursa(job #2528431)

Utilizator i.uniodCaramida Iustina-Andreea i.uniod Data 21 ianuarie 2020 21:07:51
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.12 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

const int NMAX = 5e4 + 5;
const int INF = 2e9;

struct Node{

    int node, cost;

    bool operator < (const Node other) const {
        return cost > other.cost;
    }
};

int n, m;
int dist[NMAX];
vector <Node> G[NMAX];
priority_queue <Node> pq;


void Dijkstra(int start)
{
    for(int i = 1; i <= n; ++ i)
        dist[i] = INF;

    pq.push({start,0});

    while(!pq.empty()){
        int cnode = pq.top().node;
        int cdist = pq.top().cost;
        pq.pop();

        if(dist[cnode] != INF)
            continue;

        dist[cnode] = cdist;

        for(auto it : G[cnode])
            if(dist[it.node] == INF)
                pq.push({it.node, cdist + it.cost});
    }
}

int main()
{
    int a, b, c;
    fin >> n >> m;
    for(int i = 1; i <= n; ++ i) {
        fin >> a >> b >> c;
        G[a].push_back({b,c});
    }

    Dijkstra(1);

    for(int i = 2; i <= n; ++ i)
        if(dist[i] == INF)
            fout << 0 << ' ';
        else
            fout << dist[i] << ' ';

    return 0;
}