Cod sursa(job #2207564)

Utilizator TooHappyMarchitan Teodor TooHappy Data 25 mai 2018 22:43:29
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.19 kb
#include <bits/stdc++.h>
using namespace std;
      
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");

const int inf = 1e9;

vector< vector< pair< int, int > > > G;
vector< int > dist;

void Dijkstra(int nod) {
    priority_queue< pair< int, int > > pq;
    pq.push({0, nod});
    dist[nod] = 0;

    while(!pq.empty()) {
        int tempNode = pq.top().second;
        int tempDist = -pq.top().first; pq.pop();

        if(tempDist > dist[tempNode]) {
            continue;
        }

        for(auto vecin: G[tempNode]) {
            if(dist[tempNode] + vecin.second < dist[vecin.first]) {
                dist[vecin.first] = dist[tempNode] + vecin.second;
                pq.push({-dist[vecin.first], vecin.first});
            }
        }
    }
}

int main() {
    ios::sync_with_stdio(false); in.tie(0); out.tie(0);
 
    int n, m; in >> n >> m;

    G.resize(n); dist.resize(n, inf);
    for(int i = 1; i <= m; ++i) {
        int x, y, cost; in >> x >> y >> cost;
        --x; --y;
        G[x].push_back({y, cost});
        G[y].push_back({x, cost});
    }

    Dijkstra(0);

    for(int i = 1; i < n; ++i) {
        out << dist[i] << " ";
    }
 
    in.close(); out.close();
      
    return 0;
}