Cod sursa(job #1923055)

Utilizator tudor_bonifateTudor Bonifate tudor_bonifate Data 10 martie 2017 20:28:56
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.27 kb
#include <cstdio>
#include <vector>
#include <queue>
#define INF 99999999
using namespace std;
vector < pair <int,int> > G[50005];
queue <int> Q;
int i,n,x,y,m,d[50005],exist[50005],repeat[50005],crt,node,cost,c;
bool bellman_ford()
{
    Q.push(1);
    for (i=1; i<=n; i++) d[i]=INF;
    d[1]=0;
    exist[1]=1;
    while (!Q.empty())
    {
        crt=Q.front();
        Q.pop();
        exist[crt]=0;
        for (i=0; i<G[crt].size(); i++)
        {
            node=G[crt][i].first;
            cost=G[crt][i].second;
            if (d[crt]+cost<d[node])
            {
                d[node]=d[crt]+cost;
                if (repeat[node]==n-1) return false;
                repeat[node]++;
                if (exist[node]==0)
                {
                    Q.push(node);
                    exist[node]=1;
                }
            }
        }
    }
    return true;
}
int main()
{
    freopen("bellmanford.in","r",stdin);
    freopen("bellmanford.out","w",stdout);
    scanf("%d %d",&n,&m);
    for (i=1; i<=m; i++)
    {
        scanf("%d %d %d",&x,&y,&c);
        G[x].push_back(make_pair(y,c));
    }
    if (!bellman_ford()) printf("Ciclu negativ!");
    else
        for (i=2; i<=n; i++) printf("%d ",d[i]);
    return 0;
}