Cod sursa(job #2964992)

Utilizator AlexCroitoriuAlex Croitoriu AlexCroitoriu Data 14 ianuarie 2023 11:14:20
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.35 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <utility>
#include <queue>
using namespace std;
fstream f("bellmanford.in", ios::in), g("bellmanford.out", ios::out);
#define INF 0x3f3f3f
typedef pair<int, int> ii;
int n, m;
bool cycle = 0;
vector<ii> adj[100001];
int d[100001], used[100001];
void bellmanford(int x)
{
    queue<int> q;
    q.push(x);
    for (int i = 1; i <= n; i++)
        d[i] = INF;
    d[x] = 0;
    while (!q.empty() && !cycle)
    {
        int node = q.front();
        q.pop();
        for (auto &cur : adj[node])
        {
            if (d[cur.first] > d[node] + cur.second)
            {
                d[cur.first] = d[node] + cur.second;
                q.push(cur.first);
                used[cur.first]++;
                if (used[cur.first] >= n)
                {
                    cycle = 1;
                    break;
                }
            }
        }
    }
}
signed main()
{
    f >> n >> m;
    int x, y, cost;
    while (m--)
    {
        f >> x >> y >> cost;
        adj[x].push_back(make_pair(y, cost));
    }
    bellmanford(1);
    if (cycle)
        cout << "Ciclu negativ!";
    else
    {
        for (int i = 2; i <= n; i++)
            if (d[i] == INF)
                g << 0 << ' ';
            else
                g << d[i] << ' ';
    }
}