Cod sursa(job #1705919)

Utilizator razvan3895Razvan-Mihai Chitu razvan3895 Data 21 mai 2016 07:33:21
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <fstream>
#include <iostream>
#include <vector>
#include <queue>
#include <bitset>
#include <climits>

using namespace std;

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


int n;

struct edge {
    int y;
    int c;
};

struct edge_comp {
    bool operator()(const edge &e1, const edge &e2) {
        return e1.c > e2.c;
    }
};

int main() {
    int m;

    in >> n >> m;

    vector<vector<edge> > graph(n + 1);
    vector<int> d(n + 1, INT_MAX);
    vector<int> times_selected(n + 1, 0);
    bitset<50005> in_queue(false);
    queue<int> q;
    bool negative_cycle = false;

    for (int i = 0; i < m; ++i) {
        int x, y, c;

        in >> x >> y >> c;

        edge e = {y, c};

        graph[x].push_back(e);
    }

    d[1] = 0;
    q.push(1);
    in_queue[1] = true;

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

        for (vector<edge>::iterator e = graph[node].begin(); e != graph[node].end(); ++e) {
            if (d[e->y] > d[node] + e->c) {
                d[e->y] = d[node] + e->c;

                if (!in_queue[e->y]) {
                    if (times_selected[e->y] > n) {
                        negative_cycle = true;
                    } else {
                        q.push(e->y);
                        times_selected[e->y] += 1;
                        in_queue[e->y] = true;
                    }
                }
            }
        }
    }

    if (negative_cycle) {
        out << "Ciclu negativ!\n";
        return 0;
    }

    for (int i = 2; i <= n; ++i) {
        out << d[i] << ' ';
    }

    out << '\n';

    return 0;
}