Cod sursa(job #2297447)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 5 decembrie 2018 20:54:22
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <queue>
#include <climits>

using namespace std;

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

struct Edge {
    int x, y;
    long long c;
};

int main() {

    int n, m;
    in >> n >> m;
    vector<vector<pair<int, long long>>> g(n + 1);
    vector<Edge> e(m);
    for(int i = 0; i < m; i ++) {
        int x, y, c;
        in >> x >> y >> c;
        g[x].push_back({y, c});
        e[i] = {x, y, c};
    }

    vector<long long> dist(n + 1, INT_MAX);
    vector<bool> inqueue(n + 1, 0);
    vector<int> cnt(n + 1, 0);
    dist[1] = 0;
    queue<int> q;
    q.push(1);
    inqueue[1] = 1;
    cnt[1] = 1;

    while(q.size() ) {
        int node = q.front();
        inqueue[node] = 0;
        q.pop();

        for(auto it : g[node])
            if(dist[node] < dist[it.first] - it.second) {
                dist[it.first] = dist[node] + it.second;
                if(!inqueue[it.first]) {
                    q.push(it.first);
                    cnt[it.first] ++;
                }

                if(cnt[it.first] > n) {
                    out << "Ciclu negativ!";
                    return 0;
                }
            }
    }

    for(int i = 2; i <= n; i ++)
        out << dist[i] << " ";

    return 0;
}