Cod sursa(job #2982567)

Utilizator PingStrpewpewpac PingStr Data 20 februarie 2023 14:47:41
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 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);
bool ok = 1, schimbari;


void bllmn(int stnd)
{
    dist[stnd] = 0;
    for (int i = 1; i <= n; i++)
    {
        int schimbari = 0;
        qu.push(stnd);
        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);
                    schimbari = 1;
                }
                if (i > n - 1 && (dist[nod] + cost < dist[vec]))
                {
                    ok = 0;
                    fout<<"Ciclu negativ!";
                    return;
                }
            }
        }
        if (schimbari == 0)
            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]<<" ";
        }
    }
}