Cod sursa(job #1116420)

Utilizator alexalghisiAlghisi Alessandro Paolo alexalghisi Data 22 februarie 2014 15:47:40
Problema Algoritmul Bellman-Ford Scor 20
Compilator cpp Status done
Runda Arhiva educationala Marime 1.37 kb
#include <iostream>
#include <fstream>
#include <algorithm>
#include <bitset>
#include <cstdio>
#include <vector>
#include <cmath>
#include <queue>
#include <string>
#include <cstring>
#include <map>
#include <set>


#define DN 50005
#define pb push_back
#define mp make_pair
#define per pair<int,int>
#define INF (1<<30)
#define LL long long
#define un unsigned
#define x first
#define y second
using namespace std;


int dp[DN];
queue <int> q;
vector< per > list[DN];
bitset< DN > in_q;

void bfs(int nod)
{
    q.push(nod);
    in_q[nod] = true;
    memset(dp,127,sizeof(dp));
    dp[1]=0;
    for(; q.size() && !dp[1] ; ){

        int nod = q.front();
        q.pop();
        in_q[nod] = false;
        for(int i=0;i<list[nod].size();++i){

            int next_nod = list[nod][i].x;
            int cost = list[nod][i].y;
            if( dp[next_nod] > dp[nod] + cost && !in_q[next_nod]){

                dp[next_nod] = dp[nod] + cost;
                q.push(next_nod);
                in_q[next_nod] = true;
            }

        }
    }
}


int main()
{
    int n,m;
    ifstream f("bellmanford.in");
    ofstream g("bellmanford.out");
    f>>n>>m;
    for(;m--;){
        int a,b,c;
        f>>a>>b>>c;
        list[a].pb(mp(b,c));
    }
    bfs(1);

    if(!dp[1])
        for(int i=2;i<=n;++i)
            g<<dp[i]<<" ";
            else
                g<<"Ciclu negativ!";

    return 0;
}