Cod sursa(job #2299003)

Utilizator andreiudilaUdila Andrei andreiudila Data 8 decembrie 2018 18:41:50
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.49 kb
#include <bits/stdc++.h>
#define pii pair<int,int>
#define fs first
#define sc second
#define pb push_back
#define zeros(x) x&(-x)
#define all(v) v.begin(), v.end()
#define MOD 1000000007
#define oo 2000000000
#define pii pair<int,int>
#define ll long long
#define ld long double
#define ull unsigned long long
#define mem(a) memset(a,0,sizeof(a))
#define pi 3.14159265359
#define NMax 60
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

int d[50005],nr[50005];
bool viz[50005];
vector <pair<int,int>> v[50005];
queue<int> q;
int i,j,n,m,x,y,c;

int main()
{
    fin>>n>>m;

    for(i=1; i<=m; ++i)
    {
        fin>>x>>y>>c;
        v[x].pb({y,c});
    }

    for(i=2; i<=n; ++i) d[i] = oo;
    q.push(1);
    nr[1] = 1;
    viz[1] = 1;

    while(!q.empty())
    {
        int nod = q.front();
        q.pop();
        viz[nod] = 0;

        for(auto x : v[nod])
        {
            c = x.sc;

            if(d[nod] + c < d[x.fs])
            {
                d[x.fs] = d[nod]+ c;
                if(!viz[x.fs])
                {
                    q.push(x.fs);
                    viz[x.fs] = 1;
                    nr[x.fs] ++;
                    if(nr[x.fs] == n-1)
                    {
                        fout<<"Ciclu negativ!";
                        return 0;
                    }
                }
            }
        }
    }

    for(i=2; i<=n; ++i)
        fout<<d[i]<<" ";
    return 0;
}