Cod sursa(job #2711455)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 24 februarie 2021 09:51:19
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.45 kb
#include <bits/stdc++.h>
using namespace std;

ifstream f("dijkstra.in");
ofstream g("dijkstra.out");

int n,m;
int dist[50005];
int oo=2000000007;
bool inqueue[50005];

struct compare {
    bool operator() (int a, int b) {
        return dist[a] > dist[b];
    }
};

priority_queue < int , vector < int > , compare > pq;
vector < pair < int , int > > v[50005];
int a,b,cost;

void read() {
    f >> n >> m;
    for (int i=1;i<=m;i++) {
        f >> a >> b >> cost;
        v[a].push_back({b,cost});
    }
}

void init() {
    for (int i=1;i<=n;i++) {
        dist[i] = oo;
    }
}

void dijkstra() {
    dist[1] = 0;
    pq.push(1);
    inqueue[1] = 1;
    while (pq.empty()==0) {
        int nod = pq.top();
        pq.pop();
        inqueue[nod] = 0;
        for (auto it:v[nod]) {
            int nodtoviz = it.first;
            int distance = it.second;
            if (dist[nodtoviz] > dist[nod] + distance) {
                dist[nodtoviz] = dist[nod] + distance;
                if (inqueue[nodtoviz] == 0) {
                    pq.push(nodtoviz);
                    inqueue[nodtoviz] = 1;
                }
            }
        }
    }
}

void show() {
    for (int i=2;i<=n;i++) {
        if (dist[i] == oo) {
            g << 0 << " ";
        }
        else {
            g << dist[i] << " ";
        }
    }
}

int main()
{
    read();
    init();
    dijkstra();
    show();
    return 0;
}