Cod sursa(job #2070601)

Utilizator vladcoroian2001Vlad Coroian vladcoroian2001 Data 19 noiembrie 2017 18:41:12
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.25 kb
#include <fstream>
#include <vector>
#include <queue>

using namespace std;
ifstream fi("bellmanford.in");
ofstream fo("bellmanford.out");
const int nmax=50005,INF=1<<30;
int n,m,best[nmax],updates[nmax],x,y,c;
vector <pair <int,int> > V[nmax];
queue <int> Q;
void bellmanford()
{
    while(!Q.empty())
    {
        int x=Q.front();
        Q.pop();
        for(auto edge:V[x])
        {
            int y=edge.first;
            int cost=edge.second;
            if(cost+best[x]<best[y])
            {
                Q.push(y);
                best[y]=cost+best[x];
                updates[y]++;
                if(updates[y]>=n)
                    return;
            }
        }
    }
}
int main()
{
    fi>>n>>m;
    for(int i=1;i<=m;i++)
    {
        fi>>x>>y>>c;
        V[x].push_back({y,c});
    }
    for(int i=1;i<=n;i++)
    {
        updates[i]=0;
        best[i]=INF;
    }
    best[1]=0;
    Q.push(1);
    bellmanford();
    for(int i=1;i<=n;i++)
        if(updates[i]>=n)
        {
            fo<<"Ciclu negativ!\n";
            fi.close();
            fo.close();
            return 0;
        }
    for(int i=2;i<=n;i++)
        fo<<best[i]<<" ";
    fi.close();
    fo.close();
    return 0;
}