Cod sursa(job #2113109)

Utilizator valentinoltyanOltyan Valentin valentinoltyan Data 24 ianuarie 2018 11:29:48
Problema Algoritmul Bellman-Ford Scor 15
Compilator cpp Status done
Runda Arhiva educationala Marime 1.2 kb
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define MAXN 50005
#define INF 100000000

using namespace std;

ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");

struct edge
{
    int y,cost;
};
vector <edge> graf[MAXN];
queue <int> coad;
int v[MAXN];
bool ap[MAXN];
int n,m,k;
void citire()
{
    for(int i=0;i<m;i++)
    {
        int x,y,z;
        f>>x>>y>>z;
        graf[x].push_back({y,z});
    }
    for(int i=0;i<=n;i++)
        v[i]=INF;
}

bool solve()
{
    v[1]=0;
    coad.push(1);
    while(!coad.empty())
    {
        int nod=coad.front();
        coad.pop();
        ap[nod]=0;
        k++;
        for(auto x:graf[nod])
        {
            if(v[nod]+x.cost<v[x.y])
            {
                ap[nod]=1;
                v[x.y]=v[nod]+x.cost;
                if(k>n)
                {
                    return 0;
                }
                coad.push(x.y);
            }
        }
    }
    return 1;
}
int main()
{
    f>>n>>m;
    citire();
    if(!solve())
        g<<"Ciclu negativ!";
    else
    {
        for(int i=2;i<=n;i++)
            g<<v[i]<<" ";
    }
    return 0;
}