Cod sursa(job #1379266)

Utilizator corul_barbatescUNIBUC Kira96 lockmihai corul_barbatesc Data 6 martie 2015 17:13:10
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 2.25 kb
/*
    Those without power, seek us!
    Those with power, fear us!
    We are the Order of the Black Knights!
*/

#include<fstream>
#include<cstdio>
#include<map>
#include<set>
#define FIT(a,b) for(vector<int >::iterator a=b.begin();a!=b.end();a++)
#define FITP(a,b) for(vector<pair<int,int> >::iterator a=b.begin();a!=b.end();a++)
#define RIT(a,b) for(vector<int>::reverse_iterator a=b.end();a!=b.begin();++a)
#include<stack>
#define ROF(a,b,c) for(int a=b;a>=c;--a)
#include<vector>
#include<algorithm>
#define FOR(a,b,c) for(int a=b;a<=c;++a)
#define REP(a,b) for(register int a=0;a<b;++a)
#include<cstring>
#include<ctime>
#include<bitset>
#include<cmath>
#include<iomanip>
#include<set>
#define f cin
#define g cout
#include<queue>
#define debug cerr<<"OK";
#define pii pair<int,int>
#define mp make_pair
#define pb push_back
#define fi first
#define se second
#define ll long long
#define ull unsigned int
#define mod 1000000009LL
#define SQR 350
#define db double
#define inf 1<<30
#define div fdasfasd
#define hash dsafdsfds
#define od 100003
#define mod 666013
#define DIM 60010000
#define base 256
#define bas 255
#define N 50100
#define inf 0x3f3f3f3f
#define pdd pair<double,double>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
/*
    int dx[]={0,0,0,1,-1};
    int dy[]={0,1,-1,0,0};
*/
queue<int> q;
vector<pii > v[N];
ll D[N];
int viz[N],inq[N],n,m,x,y,c;
int bfs(int x)
{
    q.push(x);
    viz[x]=1;
    inq[x]=1;
    D[x]=0;
    FOR(i,1,n)
    D[i]=(1LL<<60);
    while(!q.empty())
    {
        x=q.front();
        q.pop();
        FITP(it,v[x])
        {
            if(D[it->fi]>D[x]+it->se)
            {
                D[it->fi]=D[x]+it->se;
                viz[it->fi]++;
                if(!inq[it->fi])
                {
                    inq[it->fi]=1;
                    q.push(it->fi);
                }
                if(viz[it->fi]>n)
                    return 0;
            }
        }
    }
    return 1;
}
int main ()
{
    f>>n>>m;
    FOR(i,1,m)
    {
        f>>x>>y>>c;
        v[x].pb(mp(y,c));
    }
    if(!bfs(1))
        g<<"Ciclu negativ!";
    else
    FOR(i,2,n)
        g<<D[i]<<" ";
    return 0;
}