Cod sursa(job #2447573)

Utilizator PaterucAPetruc Andrei Stefan PaterucA Data 13 august 2019 17:51:37
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <bits/stdc++.h>

using namespace std;

ifstream inf("bellmanford.in");
ofstream outf("bellmanford.out");

const int N=50010, INF=500000000;

bool inq[N];
int tms[N], sol[N];
int n, m;
vector<pair<int,int>> v[N];

int main()
{
    inf>>n>>m;
    for(int i=1; i<=m; i++)
    {
        int x, y, z;
        inf>>x>>y>>z;
        v[x].push_back({y,z});
    }
    for(int i=1; i<=n; i++)
        sol[i]=INF;
    queue<int> q;
    tms[1]=1;
    inq[1]=1;
    sol[1]=0;
    q.push(1);
    while(!q.empty())
    {
        int tp=q.front();
        q.pop();
        if(tms[tp]>n)
        {
            outf<<"Ciclu negativ!";
            return 0;
        }
        inq[tp]=false;
        for(auto it:v[tp])
        {
            if(sol[it.first]>sol[tp]+it.second)
            {
                if(!inq[it.first])
                {
                    q.push(it.first);
                    tms[it.first]++;
                    inq[it.first]=true;
                }
                sol[it.first]=sol[tp]+it.second;
            }
        }
    }

    for(int i=2; i<=n; i++)
        outf<<sol[i]<<' ';
    return 0;
}