Cod sursa(job #3201207)

Utilizator AndreiMLCChesauan Andrei AndreiMLC Data 7 februarie 2024 09:25:55
Problema Algoritmul Bellman-Ford Scor 95
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

int n, m;
vector<pair<int, int>>G[50005];
long long dist[50005];
int inf = INT_MAX;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
bool ok;
void read() {
    f >> n >> m;
    for (int i = 0; i < m; i++) {
        int x, y, c;
        f >> x >> y >> c;
        G[x].push_back({ y, c });
    }
}
int viz[50005];

void bellmanford()
{
    queue<int>q;
    q.push(1);
    viz[1]++;
    while (!q.empty() && !ok)
    {
        int varf = q.front();
        q.pop();
        for (auto it : G[varf])
        {
            if (dist[it.first] > dist[varf] + it.second)
            {
                dist[it.first] = dist[varf] + it.second;
                viz[it.first]++;
                if (viz[it.first] == n && dist[it.first] < 0)
                {
                    ok = 1;
                }
                q.push(it.first);
            }
        }
    }
}

int main()
{
    read();
    for (int i = 2; i <= n; i++)
    {
        dist[i] = inf;
    }

    bellmanford();

    if (!ok)
    {
        for (int i = 2; i <= n; i++) {
            if (dist[i] == inf) {
                g << 0 << " ";
            }
            else {
                g << dist[i] << " ";
            }

        }
    }
    else {
        g << "Ciclu negativ!";
    }
}