Cod sursa(job #2722615)

Utilizator witekIani Ispas witek Data 13 martie 2021 02:00:50
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;

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

const int oo = 1e9;
int n, m;
vector <vector <pair <int, int> > > v;
vector <int> d, cnt;
vector <bool> inQueue;
queue <int> q;

void init() {
    v = vector <vector <pair <int, int> > > (n + 1);
    inQueue = vector <bool> (n + 1);
    cnt = vector <int> (n + 1);
    d = vector <int> (n + 1, oo);
}

bool bellmanford() {
    inQueue[1] = true;
    d[1] = 0;
    q.push(1);
    int node, otherNode, dist;
    while(!q.empty()) {
        node = q.front();
        q.pop();
        cnt[node] ++;
        if(cnt[node] >= n)
            return false;
        inQueue[node] = false;
        for(const auto& p : v[node]) {
            otherNode = p.first;
            dist = p.second;
            if(dist + d[node] < d[otherNode]) {
                d[otherNode] = dist + d[node];
                if(!inQueue[otherNode]) {
                    inQueue[otherNode] = true;
                    q.push(otherNode);
                }
            }
        }
    }
    return true;
}


void read() {
    f >> n >> m;
    init();
    int x, y, c;
    while(m--) {
        f >> x >> y >> c;
        v[x].push_back({y, c});
        //v[y].push_back({x, c});
    }
}

int main()
{
    read();
    if(bellmanford()) {
        for(int i = 2; i <= n; ++i)
            g << d[i] << " ";
    }
    else g << "Ciclu negativ!";
}