Cod sursa(job #1981009)

Utilizator NineshadowCarapcea Antonio Nineshadow Data 14 mai 2017 16:21:25
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.14 kb
#include <bits/stdc++.h>
#define MAXN 50001
#define INF 0x3f3f3f3f
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];
void djikstra(int start)
{
    int u,d,q,c,alt;
    priority_queue<edge> pq;
    for(int i=0; i<n; ++i)
        dist[i]=INF;
    dist[start]=0;
    pq.push(edge(start,0));
    while(!pq.empty())
    {
        u=pq.top().nod,c=pq.top().c;
        pq.pop();
        if(c==dist[u])
        for(edge& i : v[u])
        {
            q=i.nod,d=i.c,alt=c+d;
            if(alt<dist[q])
            {
                dist[q]=alt;
                pq.push(edge(q,dist[q]));
            }
        }
    }
}
int main()
{
    in>>n>>m;
    for(int i=0; i<m; ++i)
    {
        int a,b,c;
        in>>a>>b>>c;
        v[a-1].push_back(edge(b-1,c));
    }
    djikstra(0);
    for(int i=1; i<n; ++i)
        if(dist[i]==INF)out<<0<<' ';
        else out<<dist[i]<<' ';
    return 0;
}