Cod sursa(job #1850482)

Utilizator NineshadowCarapcea Antonio Nineshadow Data 18 ianuarie 2017 18:14:03
Problema Algoritmul lui Dijkstra Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.1 kb
#include <bits/stdc++.h>
#define MAXN 50001
#define INF 1<<30
using namespace std;
ifstream in("dijkstra.in");
ofstream out("dijkstra.out");
int n,m,dist[MAXN];
struct edge
{
    int nod,c;
    edge(int nod, int c):nod(nod),c(c) {}
    bool operator<(const edge &oth) const
    {
        return c>oth.c;
    }
};
vector<edge> v[MAXN];
priority_queue<edge> pq;
void dijkstra(int start)
{
    for(int i=1; i<=n; ++i)
        dist[i]=INF;
    dist[start]=0;
    pq.push(edge(start,0));
    while(!pq.empty())
    {
        int nod=pq.top().nod,c=pq.top().c;
        pq.pop();
        if(c==dist[nod])
        for(edge& i : v[nod])
        {
            if(dist[nod]+i.c<dist[i.nod])
            {
                dist[i.nod]=dist[nod]+i.c;
                pq.push(i);
            }
        }
    }
}
int main()
{
    in>>n>>m;
    for(int i=1; i<=m; ++i)
    {
        int a,b,c;
        in>>a>>b>>c;
        v[a].push_back(edge(b,c));
    }
    dijkstra(1);
    for(int i=2; i<=n; ++i)
        if(dist[i]==INF)out<<0<<' ';
        else out<<dist[i]<<' ';
    return 0;
}