Cod sursa(job #2374563)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 7 martie 2019 19:22:02
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.15 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <string>
#include <cstring>
#include <set>
#include <queue>
#include <map>
#include <stack>
#include <iomanip>
#define ll long long
#define lsb(x) (x & -x)

using namespace std;

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

const int INF = 1e9;

int main() {

    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);
    dist[1] = 0;
    for(int step = 1; step <= n; step ++) {
        for(int i = 1; i <= n; i ++)
            for(auto it : g[i])
                dist[it.first] = min(dist[it.first], dist[i] + it.second);
    }

    for(int i = 1; i <= n; i ++)
        for(auto it : g[i])
            if(dist[it.first] - it.second > dist[i]) {
                out << "Ciclu negativ!";
                return 0;
            }

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

    return 0;
}