Cod sursa(job #419226)

Utilizator funkydvdIancu David Traian funkydvd Data 17 martie 2010 10:15:04
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.51 kb
#include <iostream>
#include <fstream>
#include<vector>
#include<queue>
#include<algorithm>
#include<bitset>
using namespace std;
const int MAX_N = 50005;
const int INF = 0x3f3f3f3f;
vector <pair <int, int> > adj[MAX_N];
bitset <MAX_N> in_queue(false);
vector <int> dist(MAX_N, INF), cnt_in_queue(MAX_N, 0);
queue <int> Q;
int main() 
{
    ifstream in("bellmanford.in");
	ofstream out("bellmanford.out");
    int nodes, edges;
    in >>nodes >>edges;
    for (int i = 0; i < edges; ++ i) 
	{
        int x, y, c;
        in >>x>>y>>c;
        adj[x].push_back(make_pair(y, c));
    }
    int negative_cycle = false;
    dist[1] = 0, Q.push(1), in_queue[1].flip();
    while (!Q.empty() && !negative_cycle)  
	{
        int x = Q.front();
        Q.pop();
        in_queue[x] = false;
        vector < pair <int, int> >::iterator it;
        for (it = adj[x].begin(); it != adj[x].end(); ++ it) if (dist[x] < INF)
            if (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] ++;
                    }
                }
            }
    }
    if (!negative_cycle) for (int i = 2; i <= nodes; ++ i) out << dist[i] << " ";
		else out << "Ciclu negativ!\n";
    return 0;
}