Cod sursa(job #1648603)

Utilizator BaweeLazar Vlad Bawee Data 11 martie 2016 10:57:06
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.28 kb
#include <fstream>
#include <vector>
#include <algorithm>

using namespace std;

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

vector<int> heap;
vector< pair<int , int> > G[50001];
int x , y , c , n , m;
int d[50001];

bool cmp(const int& a , const int& b)
{
    return d[a] > d[b];
}

int main()
{
    f >> n >> m;
    for(int i = 1; i <= n; ++i)
    {
        f >> x >> y >> c;
        G[x].push_back(make_pair(y,c));
        G[y].push_back(make_pair(x,c));
    }

    int startNode = 1;
    for(int i = 1; i <= n; ++i) d[i] = 1 << 25;
    d[startNode] = 0;

    heap.push_back(startNode);
    make_heap(heap.begin() , heap.end() , cmp);
    while(heap.size())
    {
        int node = heap.front();
        pop_heap(heap.begin() , heap.end() , cmp);
        heap.pop_back();

        for(auto iter = G[node].begin(); iter != G[node].end(); ++iter)
            if(d[iter -> first] > d[node] + iter -> second)
            {
                d[iter -> first] = d[node] + iter -> second;
                heap.push_back(iter -> first);
                push_heap(heap.begin() , heap.end() , cmp);
            }
    }

    for(int i = 2; i <= n; ++i)
    {
        if(d[i] == 1 << 25) d[i] = 0;
        g << d[i] << " ";
    }

    return 0;
}