Cod sursa(job #2170332)

Utilizator vladdy47Bucur Vlad Andrei vladdy47 Data 14 martie 2018 23:30:43
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
# include <bits/stdc++.h>

using namespace std;

const int nmax = 1e5 * 5 + 5, inf = INT_MAX;

vector < pair <int, int> > G[nmax];
queue <int> q;

int n, m, i, d[nmax], ap[nmax];
bool sel[nmax];

void bellmanford()
{
    for (i = 1; i <= n; d[i] = inf, ++i);
    d[1] = 0, q.push(1);

    while (q.size())
    {
        int node = q.front();
        q.pop();
        sel[node] = false;

        for (auto &it: G[node])

            if (d[node] + it.second < d[it.first])
            {
                d[it.first] = d[node] + it.second;

                if (!sel[it.first])
                {
                    sel[it.first] = true;
                    q.push(it.first);

                    ap[it.first]++;

                    if (ap[it.first] > n)
                    {
                        printf("Ciclu negativ!\n");
                        return;
                    }
                }
            }
    }

    for (i = 2; i <= n; ++i)
        printf("%d ", d[i]);

    printf("\n");
}

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

    scanf("%d %d\n", &n, &m);

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

    bellmanford();

    return 0;
}