Cod sursa(job #1864980)

Utilizator tudormaximTudor Maxim tudormaxim Data 1 februarie 2017 10:22:33
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
using namespace std;

ifstream fin ("dijkstra.in");
ofstream fout ("dijkstra.out");

const int maxn = 5e4 + 5;
const int oo = 1 << 29;
vector <pair<int,int> > G[maxn];
int Dist[maxn];

void Dijkstra(int start, int n) {
    vector < pair <int,int> > :: iterator it;
    priority_queue <pair <int,int> > H;
    bitset <maxn> Vis;
    int node, i;
    for (i = 1; i <= n; i++) {
        Dist[i] = oo;
    }
    Dist[start] = 0;
    H.push(make_pair(0, start));
    while (!H.empty()) {
        node = H.top().second;
        H.pop();
        if (Vis[node] == true) {
            continue;
        }
        Vis[node] = true;
        for (it = G[node].begin(); it != G[node].end(); it++) {
            if (Dist[it->first] > Dist[node] + it->second) {
                Dist[it->first] = Dist[node] + it->second;
                H.push(make_pair(-Dist[it->first], it->first));
            }
        }
    }
}

int main() {
    ios_base :: sync_with_stdio (false);
    int n, m, x, y, c, i;
    fin >> n >> m;
    for (i = 1; i <= m; i++) {
        fin >> x >> y >> c;
        G[x].push_back(make_pair(y, c));
    }
    Dijkstra(1, n);
    for (i = 2; i <= n; i++) {
        if (Dist[i] == oo) {
            fout << "0 ";
        } else  {
            fout << Dist[i] << " ";
        }
    }
    fin.close();
    fout.close();
    return 0;
}