Cod sursa(job #2983103)

Utilizator PingStrpewpewpac PingStr Data 21 februarie 2023 17:16:32
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.13 kb
#include <bits/stdc++.h>
using namespace std;

ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");

const int SIZE = 50001;
const int INF = 1e9;

int n, x, y, z, m;
vector<pair<int,int>> gr[SIZE];
queue<int> qu;
vector<int> dist(SIZE, INF);
int inq[SIZE];
bool ok = 1;


void bllmn(int stnd)
{
    dist[stnd] = 0;
    qu.push(stnd);
    inq[stnd] = 1;
    while(!qu.empty())
    {
        int nod = qu.front();
        qu.pop();
        for (auto j: gr[nod])
        {
            int vec = j.first;
            int cost = j.second;
            if (dist[nod] + cost < dist[vec])
            {
                dist[vec] = dist[nod] + cost;
                qu.push(vec);
                inq[vec]++;
            }
            if (inq[vec] >= n)
            {
                ok = 0;
                fout<<"Ciclu negativ!";
                return;
            }
        }
    }
}

int main()
{
    fin>>n>>m;
    for (int i = 1; i <= m; i++)
    {
        fin>>x>>y>>z;
        gr[x].push_back(make_pair(y, z));
    }
    bllmn(1);
    if (ok)
    {
        for (int i = 2; i <= n; i++)
        {
            fout<<dist[i]<<" ";
        }
    }
}