Cod sursa(job #2298992)

Utilizator andreiudilaUdila Andrei andreiudila Data 8 decembrie 2018 18:34:27
Problema Algoritmul Bellman-Ford Scor 50
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.52 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];
map <pair<int,int>,int> cost;
bool viz[50005];
vector <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;
        cost[{x,y}] = c;
        v[x].pb(y);
    }

    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 = cost[ {nod,x}];

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

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