Cod sursa(job #2572937)

Utilizator alexdumitrescuDumitrescu George Alex alexdumitrescu Data 5 martie 2020 15:01:12
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.2 kb
#include <bits/stdc++.h>
#define Nmax 50005
#define pb push_back
#define mp make_pair
#define fr first
#define sc second

using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
int d[Nmax], este[Nmax], con[Nmax], n, m;
vector <pair<int, int>> v[Nmax];
queue <int> q;
int main()
{
    fin >> n >> m;
    for(int i=2;i<=n;i++)
        d[i]=INT_MAX;
    for(int i=1;i<=m;i++)
    {
        int x, y, c;
        fin >> x >> y >> c;
        v[x].pb(mp(y, c));
    }
    con[1]++;
    este[1]=1;
    q.push(1);
    while(!q.empty())
    {
        int u=q.front();
        este[u]=0;
        q.pop();
        for(auto it:v[u])
            if(d[u]+it.sc<d[it.fr])
            {
                if(!este[it.fr])
                {
                    con[it.fr]++;
                    if(con[it.fr]==n)
                    {
                        fout << "Ciclu negativ!";
                        return 0;
                    }
                    este[it.fr]=1;
                    q.push(it.fr);
                }
                d[it.fr]=d[u]+it.sc;
            }
    }
    for(int i=2;i<=n;i++)
        fout << d[i] << ' ';
    return 0;
}