Cod sursa(job #2073035)

Utilizator BogdanNeghinaNeghina Bogdan BogdanNeghina Data 22 noiembrie 2017 17:30:18
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.26 kb
#include <fstream>
#include <vector>
#include <queue>
#define infinit (1<<30)
using namespace std;
ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");
int n,m,viz[50005],d[50005];
bool einq[50005];
struct nod
{
    int x,c;
};
vector <nod> v[50005];
queue <int> q;
int bellmanford(int x)
{
    q.push(x);
    viz[x]=1;
    d[x]=0;
    einq[x]=1;
    while(!q.empty())
    {
        x=q.front();
        q.pop();einq[x]=0;
        for(int i=0;i<v[x].size();i++)
        {
            int y=v[x][i].x;
            if(d[y]>d[x]+v[x][i].c)
            {
                d[y]=d[x]+v[x][i].c;
                 viz[y]++;
                 if(viz[y]>=n-1)
                        return 0;
                if(!einq[y])
                {
                    q.push(y);
                    einq[y]=1;
                }

            }
        }
    }
    return 1;
}
void afisare()
{
    for(int i=2;i<=n;i++)
        cout<<d[i]<<" ";
}
int main ()
{
    cin>>n>>m;
    int x,y,c;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y>>c;
        v[x].push_back({y,c});
    }
    for(int i=1;i<=n;i++)
        d[i]=infinit;
    if(bellmanford(1)==0)
        cout<<"Ciclu negativ";
    else
        afisare();
    return 0;
}