Cod sursa(job #1650098)

Utilizator tudormaximTudor Maxim tudormaxim Data 11 martie 2016 16:31:08
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;

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

const int nmax = 5e4+5;
const int oo = (1<<30);
vector <pair<int,int> > g[nmax];
int dist[nmax], n;

class cmp {
public:
    inline bool operator () (const int &x, const int &y)
    {
        return dist[x] > dist[y];
    }
};

void dijkstra(int start)
{
    priority_queue <int, vector<int>, cmp> heap;
    vector <pair<int,int> > :: iterator it;
    int dad, son, cost;
    fill(dist+1, dist+n+1, oo);
    dist[start]=0;
    heap.push(start);
    while(!heap.empty())
    {
        dad=heap.top();
        heap.pop();
        for(it=g[dad].begin(); it!=g[dad].end(); it++)
        {
            son=it->first;
            cost=it->second;
            if(dist[son] > dist[dad]+cost)
            {
                dist[son]=dist[dad]+cost;
                heap.push(son);
            }
        }
    }
}

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