Cod sursa(job #1729355)

Utilizator stefanchistefan chiper stefanchi Data 14 iulie 2016 16:50:51
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.33 kb
#include <vector>
#include <queue>
#include <cstdio>
#include <utility>
#define N 50050
#define inf 10000000
using namespace std;
int n,m,dist[N];
vector <pair <int,int> > drum[N];
priority_queue <pair <int, int> > q;


void read()
{
    freopen("dijkstra.in","r",stdin);
    freopen("dijkstra.out","w",stdout);
    scanf("%d %d",&n,&m);
    int a,b,cost;
    for(int i = 2;  i <= n ; ++i)
        dist[i] = inf;
    for(int i  = 1 ; i <= m ; ++i)
    {
        scanf("%d %d %d",&a,&b,&cost);
        drum[a].push_back(make_pair(b,cost));
    }
}

void dijkstra()
{
    q.push(make_pair(0,1));
    while(!q.empty())
    {
        int vf_b = q.top().second;
        int cost = -q.top().first;
        q.pop();
        for(vector <pair <int,int> > :: iterator it = drum[vf_b].begin() ; it !=  drum[vf_b].end() ; ++it)
        {
            if(dist[it->first] > it->second + cost)
            {
                dist[it ->first] = cost + it -> second;
                q.push(make_pair(-dist[it ->first],it -> first));
            }
        }
    }

}


void afisare()
{
    for(int i = 2 ; i <= n ; i++)
    {
        if(dist[i] == inf)
            printf("%d ", 0);
        else
            printf("%d ", dist[i]);
    }
}


int main()
{
    read();
    dijkstra();
    afisare();
    return 0;
}