Cod sursa(job #879738)

Utilizator sebii_cSebastian Claici sebii_c Data 15 februarie 2013 20:21:34
Problema Algoritmul Bellman-Ford Scor 35
Compilator cpp Status done
Runda Arhiva educationala Marime 1.42 kb
#include <cstdio>

#include <queue>
#include <vector>

using namespace std;

const int MAXN = 50001;
const int INF = (int)(1e9 + 7);

int n, m;
int dist[MAXN];
int cnt[MAXN];
bool inqueue[MAXN];

vector<int> G[MAXN];
vector<int> C[MAXN];

int bellmanford()
{
    for (int i = 1; i <= n; ++i)
        dist[i] = INF;
    dist[1] = 0;

    queue<int> q;
    q.push(1);
    inqueue[1] = true;
    cnt[1] = 1;

    while (!q.empty()) {
        int node = q.front();
        q.pop();
        inqueue[node] = false;
        for (int i = 0; i < G[node].size(); ++i) {
            int next = G[node][i];
            if (dist[node] + C[node][i] < dist[next]) {
                dist[next] = dist[node] + C[node][i];
                if (!inqueue[next]) {
                    if (cnt[next] > n)
                        return -1;
                    q.push(next);
                    inqueue[next] = true;
                }
            }
        }
    }

    return 1;
}

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

    int m;
    scanf("%d %d", &n, &m);
    for (int i = 0; i < m; ++i) {
        int x, y, c;
        scanf("%d %d %d", &x, &y, &c);
        G[x].push_back(y);
        C[x].push_back(c);
    }

    if (bellmanford() == -1) {
        printf("Ciclu negativ!");
    } else {
        for (int i = 2; i <= n; ++i)
            printf("%d ", dist[i]);
        printf("\n");
    }

    return 0;
}