Cod sursa(job #1970901)

Utilizator Vlad_lsc2008Lungu Vlad Vlad_lsc2008 Data 19 aprilie 2017 18:06:15
Problema Algoritmul lui Dijkstra Scor 90
Compilator cpp Status done
Runda Arhiva educationala Marime 1.38 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <bitset>
#include <queue>
using namespace std;

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

const int maxn = 5e4 + 5;
const int maxm = 25e4 + 5;
const int oo = 1 << 30;
vector <pair <int,int> > G[maxn];
int Dist[maxn];
int n, m;

class mycomp
{
public:
    bool operator () (int a,int b)
    {
        return Dist[a]>=Dist[b];
    }
};


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

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