Cod sursa(job #2702749)

Utilizator shumsterVasile Mihai shumster Data 5 februarie 2021 18:35:08
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.32 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <string>
#include <cstring>
#include <queue>
 
using namespace std;
 
const int INF = 1e9 + 5;
 
int main() {
    ifstream in("bellmanford.in");
    ofstream out("bellmanford.out");
 
    int n, m;
    in >> n >> m;
    vector<vector<pair<int, int>>> g(n + 1);
    for(int i = 1; i <= m; i ++) {
        int x, y, c;
        in >> x >> y >> c;
        g[x].push_back({y, c});
    }
 
    vector<int> dist(n + 1, INF);
    queue<int> q;
    vector<bool> inq(n + 1, 0);
    vector<int> cnt(n + 1, 0);
    //inq[1] = 1;
    dist[1] = 0;
    q.push(1);
 
    while(q.size()) {
        auto from = q.front();
        q.pop();
        inq[from] = 0;
 
        for(auto it : g[from]) {
            if(dist[it.first] > dist[from] + it.second) {
                dist[it.first] = dist[from] + it.second;
 
                if(!inq[it.first]) {
                    inq[it.first] = 1;
                    cnt[it.first] ++;
                    q.push(it.first);
 
                    if(cnt[it.first] >= n) {
                        out << "Ciclu negativ!";
                        return 0;
                    }
                }
            }
        }
    }
    for(int i = 2; i <= n; i ++)
        out << dist[i] << " ";
 
    return 0;
}