Cod sursa(job #394267)

Utilizator xtremespeedzeal xtreme Data 10 februarie 2010 17:51:33
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 2.34 kb
#include <fstream.h>
#include <iostream.h>
#include <queue>
#include <bitset>
#include <algorithm>
#include <cassert>
using namespace std;

const char iname[] = "bellmanford.in";
const char oname[] = "bellmanford.out";

const int MAX_N = 50005;
const int INF = 0x3f3f3f3f;

vector < pair <int, int> > adj[MAX_N];

int main(void) 
     {ifstream in(iname);
      int nodes, edges;
      int x, y, c;

    
      in >> nodes >> edges;                            //citire si creare graf
      for(int i = 0; i < edges; ++ i) 
                 {in >> x >> y >> c;
        	  adj[x].push_back(make_pair(y, c));
                 }
      in.close();

      queue <int> Q;
      bitset <MAX_N> in_queue(false);
      vector <int> dist(MAX_N, INF), cnt_in_queue(MAX_N, 0);
      int negative_cycle = false;
      vector < pair <int, int> >::iterator it;


      dist[1] = 0, Q.push(1), in_queue[1].flip();    //initializare
    
      while (!Q.empty() && !negative_cycle)  
                  {int x = Q.front();
                   Q.pop();
                   in_queue[x] = false;
                   for (it = adj[x].begin(); it != adj[x].end(); ++ it) 
                   	             if (dist[x] < INF && dist[it->first] > dist[x] + it->second) 
				                           {dist[it->first] = dist[x] + it->second;
                                            if (!in_queue[it->first]) 
                                                   {if (cnt_in_queue[it->first] > nodes)     negative_cycle = true;
                                                    else                                    {Q.push(it->first);
       	                            		                                                 in_queue[it->first] = true;
                          		                     	                                     cnt_in_queue[it->first] ++;
                                                                                            }
                                                   }
                                           }
		          }

      ofstream out(oname);                               //scrierea datelor de iesire
      if (!negative_cycle) 
             for (int i = 2; i <= nodes; ++ i)
                out << dist[i] << " ";
      else
              out << "Ciclu negativ!\n";
    out.close();

    return 0;
}