Cod sursa(job #1377689)

Utilizator Al3ks1002Alex Cociorva Al3ks1002 Data 5 martie 2015 23:45:51
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.63 kb
#include<cstdio>
#include<fstream>
#include<iostream>
#include<iomanip>
#include<algorithm>
#include<vector>
#include<bitset>
#include<deque>
#include<queue>
#include<set>
#include<map>
#include<cmath>
#include<cstring>
#include<ctime>
#include<cstdlib>
#include<unordered_map>

#define ll long long
#define pb push_back
#define mp make_pair
#define pii pair<int,int>
#define pll pair<ll,ll>
#define all(x) (x).begin(), (x).end()
#define fi first
#define se second

using namespace std;

const int nmax = 50005;
const int inf = 1 << 30;

int i, n, m, x, y, z, cnt[nmax], d[nmax];

vector<pii> v[nmax];
bitset<nmax> inq;
deque<int> q;

void bf(int source)
{
    for(i = 1; i <= n; i++)
        d[i] = inf;

    d[source] = 0;
    q.pb(source);
    inq[source] = 1;

    while(!q.empty())
    {
        x = q.front();
        q.pop_front();
        inq[x] = 0;

        cnt[x]++;
        if(cnt[x] == n + 1)
        {
            printf("Ciclu negativ!\n");
            return;
        }

        for(auto it : v[x])
            if(d[x] + it.se < d[it.fi])
            {
                d[it.fi] = d[x] + it.se;
                if(!inq[it.fi])
                {
                    inq[it.fi] = 1;
                    q.pb(it.fi);
                }
            }
    }

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

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

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

    for(; m; m--)
    {
        scanf("%d%d%d", &x, &y, &z);
        v[x].pb(mp(y, z));
    }

    bf(1);

    return 0;
}