Cod sursa(job #640264)

Utilizator sternvladStern Vlad sternvlad Data 25 noiembrie 2011 01:15:59
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.52 kb
using namespace std;
#include<iostream>
#include<fstream>
#include<vector>
#include<queue>
#define pb push_back
#define nmax 50010
#define oo 0x3f3f3f3f
struct nod{
    int lg,c;
};
vector<nod> G[nmax];
int isinq[nmax],dp[nmax],nr[nmax],N,M;
ofstream fout("bellmanford.out");
queue<int> q;
int ok;
void solve()
{   int i;
    for(i=0;i<=N;i++)
    {
        dp[i]=oo;
        nr[i]=0;
    }
    dp[1]=0;
    q.push(1);
    isinq[1]=1;
    nr[1]=1;
    ok=1;
    int u;
    vector<nod>::iterator it;
   while(!q.empty() && ok)
   {
       u=q.front();
       q.pop();
       isinq[u]=0;
       for(it=G[u].begin();it<G[u].end();it++)
       {
           if(dp[it->lg]>dp[u]+it->c)
           {
               dp[it->lg]=dp[u]+it->c;
               if(!isinq[it->lg])
               {
                   q.push(it->lg);
                   isinq[it->lg]=1;
                   nr[it->lg]++;
                   if(nr[it->lg]>N)
                   {
                       ok=0;
                   }

               }
           }
       }

   }
   if(ok==0)
   {
       fout<<"Ciclu negativ!\n";
   }
   else{
       for(i=2;i<=N;i++)
       {
           fout<<dp[i]<<" ";
       }
       fout<<"\n";
   }

}

void cit()
{
    ifstream fin("bellmanford.in");

    int i,x,y,c;
    fin>>N>>M;
    for(i=1;i<=M;i++)
    {
        fin>>x>>y>>c;
        G[x].pb((nod){y,c});
    }

    fin.close();
}

int main()
{
    cit();
    solve();
    fout.close();
    return 0;
}