Cod sursa(job #1649658)

Utilizator gabib97Gabriel Boroghina gabib97 Data 11 martie 2016 14:30:07
Problema Algoritmul lui Dijkstra Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.15 kb
#include <stdio.h>
#include <vector>
#include <queue>
#define inf 1000000000
using namespace std;
int n,m,i,x,y,c,d[50001];
bool o[50001];
vector<pair<int,int> > G[50001];
queue<int> Q;
void bellman_ford(int s)
{
    int i,z,x,y,c;
    for (i=1;i<=n;i++) d[i]=inf;
    d[s]=0; Q.push(s); o[s]=1;
    while (!Q.empty())
    {
        x=Q.front();
        o[x]=0;
        Q.pop();
        z=G[x].size();
        for (i=0;i<z;i++)
        {
            y=G[x][i].first;
            c=G[x][i].second;
            if (d[y]>d[x]+c)
            {
                d[y]=d[x]+c;
                if (!o[y])
                {
                    Q.push(y);
                    o[y]=1;
                }
            }
        }
    }
}
int main()
{
    freopen ("dijkstra.in","r",stdin);
    freopen ("dijkstra.out","w",stdout);
    scanf("%i%i",&n,&m);
    for (i=1;i<=m;i++)
    {
        scanf("%i%i%i",&x,&y,&c);
        G[x].push_back(make_pair(y,c));
    }
    bellman_ford(1);
    for (i=2;i<=n;i++)
        if (d[i]==inf) printf("0 ");
        else printf("%i ",d[i]);
    fclose(stdin);
    fclose(stdout);
    return 0;
}