Cod sursa(job #3251606)

Utilizator Xutzu358Ignat Alex Xutzu358 Data 26 octombrie 2024 11:36:22
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.25 kb
#include <vector>
#include <queue>
#include <fstream>
using namespace std;

ifstream f("bellmanford.in");
ofstream g("bellmanford.out");

int oo=2000000009;
queue < int > q;
vector < pair < int , int > > v[50005];
int dist[50005];
int n, m, x, y, c;
int ok=1;
int viz[50005];
int inqueue[50005];

int main()
{
    f >> n >> m;
    for (int i=1;i<=m;i++) {
        f >> x >> y >> c;
        v[x].push_back({y, c});
    }
    for (int i=1;i<=n;i++) {
        dist[i] = oo;
    }
    dist[1] = 0;
    q.push(1);
    inqueue[1] = 1;
    while (!q.empty() && ok == 1) {
        int nod = q.front();
        q.pop();
        inqueue[nod] = 0;
        viz[nod]++;
        if (viz[nod] >= n) {
            ok = 0;
            break;
        }
        for (auto ed: v[nod]) {
            if (dist[ed.first] > dist[nod] + ed.second) {
                dist[ed.first] = dist[nod] + ed.second;
                if (inqueue[ed.first] == 0) {
                    q.push(ed.first);
                    inqueue[ed.first] = 1;
                }
            }
        }
    }
    if (ok == 1) {
        for (int i=2;i<=n;i++) {
            g << dist[i]<<" ";
        }
    }
    else {
        g << "Ciclu negativ!";
    }
    return 0;
}