Cod sursa(job #1397855)

Utilizator obidanDan Ganea obidan Data 23 martie 2015 19:57:57
Problema Algoritmul lui Dijkstra Scor 10
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
using namespace std;

#define pll pair<long,long>
#define pi pair<int,int>
#define INF (1<<30) + 1
const int NMax = 50002;

vector< pair<int,int> > G[NMax];
int used[NMax];
int d[NMax];
int n,m;
void dijkstra(int source)
{
    int i;
    priority_queue< pi , vector< pi > ,greater< pi > > Heap;
    for(i = 1; i <= n; i++) d[i] = INF;
    pi newpair = {0,source};
    d[source] = 0;
    Heap.push(newpair);
    int from;
    while(!Heap.empty())
    {
        from = Heap.top().second;
        Heap.pop();
        if(used[from]) continue;
        used[from] = 1;
        for(auto it = G[from].begin(); it != G[from].end(); it++)
        {
            if(d[it->first] > d[from] + it-> second)
            {
                d[it->first] = d[from] + it->second;
                Heap.push(make_pair(d[it->first],it->first));
            }
        }
    }
}

int main()
{
    int i;
    ifstream f("dijkstra.in");
    ofstream g("dijkstra.out");
    f>>n>>m;
    int x,y,c;
    for(i = 1; i <= m; i++)
    {
        f>>x>>y>>c;
        G[x].push_back(make_pair(y,c));
    }
    dijkstra(1);
    for(i = 2 ; i <= n; i++)
    {
        g<<d[i]<<" ";
    }
}