Cod sursa(job #1105355)

Utilizator Dddarius95Darius-Florentin Neatu Dddarius95 Data 11 februarie 2014 19:00:10
Problema Algoritmul Bellman-Ford Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.7 kb
// Bellman Ford - O(M*N*logN)
#include <fstream>
#include <vector>
#include <queue>
#include <bitset>
#define Nmax 50099
#define Mmax 250099
#define pb push_back
#define mp make_pair
#define x first
#define c second
#define oo 2000000000
using namespace std;
ifstream f("bellmanford.in") ;
ofstream g("bellmanford.out");

int N,M,d[Nmax],cicluNegativ;
typedef pair<int,int> edge;
vector < edge > G[Nmax];
struct cmp
{
     bool operator()(const int &a,const int &b)const
     {
          return (d[a]>d[b]);
     };
};

priority_queue< int , vector< int > , cmp >  pq;
bitset < Nmax > inHeap;
void ReadInput()
{
     f>>N>>M;
     for(int i=1;i<=N;++i)d[i]=oo;
     for(int i=1;i<=M;++i)
     {
          int x,y,c;
          f>>x>>y>>c;
          G[x].pb(edge(y,c)) ;
          G[y].pb(edge(x,c));
          if(x==1)d[y]=c;
          if(y==1)d[x]=c;
     }
}

void Bellman()
{
     d[1]=0;
     for(int i=2;i<=N;++i)pq.push(i),inHeap[i]=1;
     for(;!pq.empty();pq.pop())
     {
          int node=pq.top();
          inHeap[node]=0;
          for(vector<edge>::iterator it=G[node].begin();it!=G[node].end();++it)
               if(d[node]+it->c < d[it->x])
               {
                    d[it->x]=d[node]+it->c;
                    if(!inHeap[it->x])
                    {
                         inHeap[it->x]=1;
                         pq.push(it->x);
                    }
               }
     }
     for(int i=2;i<=N;++i)
          if(d[i]==oo)d[i]=0;
}

void PrintOutput()
{
     for(int i=2;i<=N;++i)g<<d[i]<<' ';
     g<<'\n';
}
int main()
{
     ReadInput();
     Bellman();
     PrintOutput();
     f.close();g.close();
     return 0;
}