Cod sursa(job #1535860)

Utilizator AlexNiuclaeNiculae Alexandru Vlad AlexNiuclae Data 25 noiembrie 2015 12:05:20
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.34 kb
///mr robot
#include <bits/stdc++.h>

using namespace std;

const int Nmax = 50000 + 10;
const int inf = 0x3f3f3f3f;

int n , m , i , S;
int nr[Nmax] , bst[Nmax];

bool marked[Nmax] , cycle;

vector < pair < int , int > > g[Nmax];
queue < int > q;

void Bford()
{
    memset(bst , inf , sizeof(bst));
    for (q.push(S),marked[S]=1,bst[S]=0; !q.empty(); q.pop())
    {
        int node = q.front(); marked[node] = 0;

        for (auto &it : g[node])
        {
            int newN , crtCost; tie(newN , crtCost) = it;
            if (bst[newN] > bst[node] + crtCost)
            {
                if (nr[newN] == n-1)
                {
                    printf("Ciclu negativ!\n"); cycle = 1;
                    return;
                }
                nr[newN]++;
                bst[newN] = bst[node] + crtCost;
                if (!marked[newN]) marked[newN] = 1, q.push(newN);
            }
        }
    }
}

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

    scanf("%d %d", &n, &m); S = 1;
    for (i = 1 ; i <= m; ++i)
    {
        int node1, node2, cost;
        scanf("%d %d %d", &node1, &node2, &cost);

        g[node1].push_back({node2 , cost});
    }

    Bford();
    for (i = 2; i <= n && !cycle; ++i) printf("%d ", bst[i]);

    return 0;
}