Cod sursa(job #2401629)

Utilizator alexdumitrescuDumitrescu George Alex alexdumitrescu Data 9 aprilie 2019 21:04:22
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.18 kb
#include <bits/stdc++.h>
#define Nmax 50005
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
struct muchie
{
    int y, c;
};
vector <muchie> v[Nmax];
queue <int> q;
bool este[Nmax];
int n, m, i, x, y, c, ap[Nmax], d[Nmax], u;
int main()
{
    fin >> n >> m;
    for(i=1;i<=m;i++)
    {
        fin >> x >> y >> c;
        v[x].push_back({y, c});
    }
    for(i=2;i<=n;i++)
        d[i]=INT_MAX;

    q.push(1);
    ap[1]++;
    este[1]=1;

    while(!q.empty())
    {
        u=q.front();
        este[u]=0;
        q.pop();

        for(i=0;i<v[u].size();i++)
            if(d[v[u][i].y]>d[u]+v[u][i].c)
            {
                d[v[u][i].y]=d[u]+v[u][i].c;
                if(este[v[u][i].y]==0)
                {
                    ap[v[u][i].y]++;
                    este[v[u][i].y]=0;
                    if(ap[v[u][i].y]==n)
                    {
                        fout << "Ciclu negativ";
                        return 0;
                    }
                    q.push(v[u][i].y);
                }
            }
    }
    for(i=2;i<=n;i++)
        fout << d[i] << ' ';
    return 0;
}