Cod sursa(job #554736)

Utilizator tinkyAndrei Ilisei tinky Data 15 martie 2011 08:54:57
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.04 kb
#include<fstream>
#include<vector>
#include<queue>
#define nmn 50002
#define pb push_back
using namespace std;
vector<int> v[nmn];
vector<int> c[nmn];
queue<int> q;
int n,m;
int d[nmn];
int viz[nmn];
void citire()
{
	int i,x,y,cost;
	ifstream in("bellmanford.in");
	in>>n>>m;
	for (i=1;i<=m;i++)
	{
		in>>x>>y>>cost;
		v[x].pb(y);
		c[x].pb(cost);
	}
}

void afisare()
{
	int i;
	ofstream out("bellmanford.out");
	for (i=2;i<=n;i++)
		out<<d[i]<<" ";
	out<<'\n';
}
void af()
{
	ofstream out("bellmanford.out");
	out<<"Ciclu negativ!\n";
}
int main()
{
	int i,j,x,y,ok=1;
	citire();
	q.push(1);
	viz[1]=1;
	while (!q.empty()&&ok)
	{
		x=q.front();
		q.pop();
		for (i=0;i<(int)v[x].size();i++)
		{
			y=v[x][i];
			if (!viz[y])
			{
				viz[y]++;
				d[y]=d[x]+c[x][i];
				q.push(y);
			}
			else if(d[y]>c[x][i]+d[x])
			{
				d[y]=d[x]+c[x][i];
				q.push(y);
				viz[y]++;
				
			}
			if (viz[y]>n)
				ok=0;
		}
	}
	if (ok)
		afisare();
	else 
		af();
	return 0;
}