Cod sursa(job #869272)

Utilizator TodeaDariustodea darius TodeaDarius Data 1 februarie 2013 12:13:46
Problema Algoritmul Bellman-Ford Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.21 kb
#include<fstream>
#include<queue>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
#define nmax 50010
int ok[nmax],nok[nmax],dist[nmax],n,m,i,e;
struct nod
{
    int nr,cst;
    nod *adr;
} *a[nmax];
queue <int> q;
void citire()
{
    f>>n>>m;
    for(int i=1;i<=m;i++)
    {
        int x,y,z;
        f>>x>>y>>z;
        nod *p=new nod;
        p->nr=y;
        p->cst=z;
        p->adr=a[x];
        a[x]=p;
    }
}
void parcurgere()
{
	int x;
	while(!q.empty() && e==0)
	{
		x=q.front();
		for(nod *p=a[x];p!=NULL;p=p->adr)
		{
			if(dist[p->nr]>dist[x]+p->cst)
			{
				nok[p->nr]++;
				if(nok[p->nr]==n)
				{
					g<<"Ciclu negativ!";
					e=1;
				}
				dist[p->nr]=dist[x]+p->cst;
				if(ok[p->nr]==0)
				{
					ok[p->nr]=1;
					q.push(p->nr);
				}
			}
		}
		q.pop();
		ok[x]=0;
	}
    //if(!q.empty() && e==0)
    //    parcurgere(q.front());
}
int main()
{
    citire();
    for(i=2;i<=n;i++)
        dist[i]=50000000;
    q.push(1);
	parcurgere();
    if(e==1)
        return 0;
    for(i=2;i<=n;i++)
    {
        if(dist[i]==50000000)
            g<<0;
        else
            g<<dist[i]<<' ';
    }
    return 0;
}