Cod sursa(job #3231906)

Utilizator andreifilimonPopescu Filimon Andrei Cosmin andreifilimon Data 28 mai 2024 09:30:02
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.22 kb
#include <fstream>
#include <queue>
#include <vector>

using namespace std;

ifstream cin("bellmanford.in");
ofstream cout("bellmanford.out");

#define MAXN 50000
#define MAXM 250000
#define INF 250000000

vector<pair<int, int>> v[MAXN + 1];
queue<int> q;
vector<int> dist(MAXN + 1, INF);
int f[MAXN + 1];
int n, m;

void bellmanford(int poz)
{
    int x, y, c, check;
    check = 0;
    dist[poz] = 0;
    q.push(poz);
    while (!q.empty() && check == 0)
    {
        x = q.front();
        q.pop();
        for (auto i : v[x])
        {
            y = i.first;
            c = i.second;
            if (dist[y] > dist[x] + c)
            {
                q.push(y);
                f[y]++;
                if (f[y] == n)
                    check = 1;
                dist[y] = dist[x] + c;
            }
        }
    }
    if (check == 0)
    {
        int i;
        for (i = 1; i <= n; i++)
            if (i != poz)
                cout<<dist[i]<<" ";
    }
    else
        cout << "Ciclu negativ!";
}

int main()
{
    cin >> n >> m;
    int i, x, y, c;
    for (i = 0; i < m; i++)
    {
        cin >> x >> y >> c;
        v[x].push_back({y, c});
    }
    bellmanford(1);
}