Cod sursa(job #2965849)

Utilizator vlad414141414141Vlad Ionescu vlad414141414141 Data 16 ianuarie 2023 13:04:57
Problema Algoritmul Bellman-Ford Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.39 kb
#include <iostream>
#include <bits/stdc++.h>

using namespace std;

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

int n, m, x, y, z;
vector<pair<int, int>> g[50001];
vector<int> dist(50001, INT_MAX), nr(50001);
vector <double> dist2(50001, INT_MAX);
queue<int> q;
bool viz[50001];

bool bellmanford() {
    q.push(1);
    dist[1] = 0;

    while (!q.empty()) {
        int t = q.front();
        q.pop();
        viz[t] = 0;

        for (auto& x : g[t]) {
            if (dist[x.first] > dist[t] + x.second) {
                nr[x.first]++;
                if (dist2[x.first]!=dist2[t]) {
                    return 0;
                }

                dist[x.first] = dist[t] + x.second;
                if (x.second<0)
                    dist2[x.first]=dist2[t] + x.second/100;
                else
                    dist2[x.first]=dist2[t] + x.second;

                if (!viz[x.first]) {
                    q.push(x.first);
                }
                viz[x.first] = 1;
            }
        }
    }

    return 1;
}

int main() {
    fin >> n >> m;
    for (int i = 0; i < m; i++) {
        fin >> x >> y >> z;
        g[x].push_back(make_pair(y, z));
    }
    if (bellmanford()) {
        for (int i = 2; i <= n; i++) {
            fout << dist[i] << " ";
        }
    } else {
        fout << "Ciclu negativ!";
    }
}