Cod sursa(job #1842591)

Utilizator alex_topTop Alexandru alex_top Data 7 ianuarie 2017 11:51:14
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.35 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
#define NMAX 50005
#define inf 2000000000
using namespace std;
ifstream f("dijkstra.in");
ofstream g("dijkstra.out");
int n,m,x,y,z,i,j,d[NMAX];
bool visited[NMAX];
vector <pair <int, int> >v[NMAX];
struct comp
{
    bool operator ()(pair <int,int> a, pair <int,int>b)
    {
        return a.second>b.second;
    }
};
priority_queue <pair <int, int> , vector <pair <int,int>>,comp> pq;

void dijkstra()
{
    for(i=1;i<=n;i++) d[i]=inf;
    d[1]=0;
    pq.push({1,0});
    while(!pq.empty())
    {
        pair <int,int> curr=pq.top();
        pq.pop();
        if(!visited[curr.first])
        {
            visited[curr.first]=1;
            for(auto & it : v[curr.first])
            {
                if(!visited[it.first] && d[it.first] > d[curr.first] + it.second)
                {
                    d[it.first] = d[curr.first] + it.second;
                    pq.push({it.first, d[it.first]});
                }
            }
        }
    }
}

int main()
{
    f>>n>>m;
    for(i=1;i<=m;i++)
    {
        f>>x>>y>>z;
        v[x].push_back({y,z});
    }
    dijkstra();
    for(i=2;i<=n;i++)
    {
        if(d[i]!=inf)
        {
            g<<d[i]<<" ";
        }
        else g<<0<<" ";
    }
    return 0;
}