Cod sursa(job #2529660)

Utilizator i.uniodCaramida Iustina-Andreea i.uniod Data 23 ianuarie 2020 19:22:15
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.16 kb
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("dijkstra.in");
ofstream fout("dijkstra.out");

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

struct NodeStruct {

    int node, cost;

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

int N, M;
int dist[NMAX + 5];
vector <NodeStruct> G[NMAX + 5];
priority_queue <NodeStruct> pq;

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

    pq.push({s, 0});

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

        if(dist[cnode] == INF) {
            dist[cnode] = cdist;

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

    for(int i = 1; i <= N; ++ i)
        if(dist[i] == INF)
            dist[i] = 0;
}

int main()
{
    fin >> N >> M;

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

    Dijkstra(1);

    for(int i = 2; i <= N; ++ i)
        fout << dist[i] << ' ';
    return 0;
}