Cod sursa(job #2027106)

Utilizator MarinPeptenaruMarin Vasile Peptenaru MarinPeptenaru Data 25 septembrie 2017 17:19:01
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>

using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int viz[50002];
int dist[50002];
struct arc
{
    int x, c;
};
vector < arc > v[50002];
queue < int > q;
int n,m,x,y,z;
int main()
{
    in>>n>>m;
    for(int i=1; i<=m; i++)
    {
        in>>x>>y>>z;
        v[x].push_back({y,z});
    }
    for(int i=1; i<=n; i++)
        dist[i]=INT_MAX;
    dist[1]=0;
    q.push(1);
    while(!q.empty())
    {
        int i=q.front();
        q.pop();
        viz[i]++;
        if(viz[i]==n)
        {
            out<<"Ciclu negativ!";
            return 0;
        }
        m=v[i].size();
        for(int k=0; k<m; k++)
        {
            int j=v[i].at(k).x;
            int c=v[i].at(k).c;
            if(dist[j]>dist[i]+c)
            {
                dist[j]=dist[i]+c;
                q.push(j);
            }
        }
    }
    for(int i=2; i<=n; i++)
        out<<dist[i]<<' ';
    return 0;
}