Cod sursa(job #1714776)

Utilizator Alexghita96Ghita Alexandru Alexghita96 Data 9 iunie 2016 13:36:55
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.64 kb
#include <cstdio>
#include <vector>
#include <queue>
#include <cstring>

#define NMAX 50005
#define INF 0x3F3F3F3F

using namespace std;

int N, M, cost[NMAX], noUsed;
bool negativeCycle, used[NMAX];
vector <pair <int, int> > graph[NMAX];

void read() {
    int x, y, c;

    scanf("%d %d", &N, &M);

    for (int i = 1; i <= M; ++i) {
        scanf("%d %d %d", &x, &y, &c);
        graph[x].push_back(make_pair(c, y));
    }
    memset(cost, INF, sizeof(cost));
}

void bellmanFord(int root) {
    queue <int> q;
    vector <pair <int, int> > :: iterator it;
    int node;

    q.push(root);
    used[root] = true;
    noUsed++;
    cost[root] = 0;

    while (!q.empty()) {
        if (noUsed > N) {
            negativeCycle = true;
            return;
        }

        node = q.front();
        q.pop();
        used[node] = false;
        noUsed--;

        for (it = graph[node].begin(); it != graph[node].end(); ++it) {
            if (cost[it -> second] > cost[node] + it -> first) {
                cost[it -> second] = cost[node] + it -> first;
                if (!used[it -> second]) {
                    q.push(it -> second);
                    used[it -> second] = true;
                    noUsed++;
                }
            }
        }
    }
}

void print() {
    if (negativeCycle) {
        printf("Ciclu negativ!");
    }
    else {
        for (int i = 2; i <= N; ++i) {
            printf("%d ", cost[i]);
        }
    }
}

int main() {
    freopen("bellmanford.in", "r", stdin);
    freopen("bellmanford.out", "w", stdout);

    read();
    bellmanFord(1);
    print();
}