Cod sursa(job #2371011)

Utilizator catalintermureTermure Catalin catalintermure Data 6 martie 2019 15:06:14
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.34 kb
#include <bits/stdc++.h>

using namespace std;

ifstream inf("dijkstra.in");
ofstream outf("dijkstra.out");

int dist[50001];
bool viz[50001];

const int INF = 1 << 30;

vector< pair<int,int> > v[50001];

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

priority_queue<int, vector<int>, comp > pq;


void dijkstra(int x) {
    dist[x] = 0;
    pq.push(x);
    viz[x] = 1;
    while(!pq.empty()) {
        x = pq.top();
        pq.pop();
        viz[x] = 0;
        for(int i = 0; i < v[x].size(); i++) {
            int vec = v[x][i].first;
            int cost = v[x][i].second;
            if(dist[x] + cost < dist[vec]) {
                dist[vec] = dist[x] + cost;
                if(viz[vec] == 0) {
                    pq.push(vec);
                    viz[vec] = 1;
                }
            }
        }
    }
}

int main() {
    int n, m;
    inf >> n >> m;
    for(int i = 1; i <= m; i++) {
        int x, y, c;
        inf >> x >> y >> c;
        v[x].push_back(make_pair(y,c));
    }
    for(int i = 1; i <= n; i++) {
        dist[i] = INF;
    }
    dijkstra(1);
    for(int i = 2; i <= n; i++) {
        if(dist[i] == INF) {
            outf << "0 ";
        }
        else {
            outf << dist[i] << ' ';
        }
    }
    return 0;
}