Cod sursa(job #1863707)

Utilizator roxannemafteiuMafteiu-Scai Roxana roxannemafteiu Data 31 ianuarie 2017 09:39:37
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <bits/stdc++.h>

using namespace std;

const int N_MAX = 50005;
const int INF = 0x3f3f3f3f;

int n, m;
bool negative_cycle;

int dist[N_MAX], counter[N_MAX];

vector <pair <int, int>> graph[N_MAX];
bool in_q[N_MAX];
queue <int> q;

void read() {
    ifstream fin("bellmanford.in");

    int x, y, c;

    fin >> n >> m;
    while (m--) {
        fin >> x >> y >> c;
        graph[x].emplace_back(y, c);
    }

    fin.close();
}

inline void bellmanford(int node, int cost) {
    if (cost < dist[node]) {
        dist[node] = cost;
        if (!in_q[node]) {
            q.push(node);
            in_q[node] = true;
            ++counter[node];
            if (counter[node] == n) {
                negative_cycle = true;
            }
        }
    }
}

inline void solve() {
    int node;

    memset(dist, INF, sizeof dist);
    dist[1] = 0;
    q.push(1);
    in_q[1] = true;
    counter[1] = n  - 1;

    while (!q.empty() && !negative_cycle) {
        node = q.front();
        q.pop();
        in_q[node] = false;

        for (const auto &son : graph[node]) {
           bellmanford(son.first, dist[node] + son.second);
        }
    }
}

void write() {
    ofstream fout("bellmanford.out");

    if (negative_cycle) {
        fout << "Ciclu negativ";
    } else {
        for (int i = 2; i <= n; ++i) {
            fout << dist[i] << " ";
        }
    }

    fout.close();
}

int main() {
    read();
    solve();
    write();
    return 0;
}