Cod sursa(job #2528449)

Utilizator i.uniodCaramida Iustina-Andreea i.uniod Data 21 ianuarie 2020 21:29:18
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.14 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 NodeCost{

    int node, cost;

    bool operator < (const NodeCost other) const {

        return cost > other.cost;

    }
};

int N, M;
vector <NodeCost> g[NMAX + 5];
int dist[NMAX + 5];

priority_queue <NodeCost> 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)
            continue;

        dist[cnode] = cdist;

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

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++)
        if(dist[i] == INF)
            fout << 0 << ' ';
        else
            fout << dist[i] << ' ';

    return 0;
}