Pagini recente » Cod sursa (job #1376311) | Cod sursa (job #2504054) | Cod sursa (job #990284) | Cod sursa (job #841807) | Cod sursa (job #679658)
Cod sursa(job #679658)
#include<stdio.h>
#include<vector>
#include<queue>
#include<bitset>
#define Nmax 50001
#define INF 0x3f3f3f3f
using namespace std;
int N,M,S,nr_in_q[Nmax],d[Nmax];
vector< pair<int,int> > G[Nmax];
bitset<Nmax> in_q;
void read()
{
FILE*f = fopen("bellmanford.in","r");
fscanf(f,"%d%d",&N,&M);
int i,x,y,c;
S=1;
for(i=1;i<=M;++i)
{
fscanf(f,"%d%d%d",&x,&y,&c);
G[x].push_back( make_pair(y,c) );
}
fclose(f);
}
int bellman_ford(int S)
{
int i;
fill(d+1,d+N+1,INF);
d[S] = 0;
queue<int> Q;
Q.push(S);in_q[S] = true;
bool negative = false;
int nod;
while(!Q.empty() && negative == false)
{
nod = Q.front();
Q.pop();
in_q[nod] = false;
for(vector< pair<int,int> >::iterator it = G[nod].begin(); it != G[nod].end();++it)
{
if( d[ it->first ] > d[nod] + it->second )
{
d[ it->first ] = d[nod] + it->second;
if(in_q[it->first] == false)
{
if(nr_in_q[it->first] > N)
negative = true;
else
{
Q.push(it->first);
in_q[it->first] = true;
++nr_in_q[it->first];
}
}
}
}
}
return negative;
}
int main()
{
read();
FILE*g = fopen("bellmanford.out","w");
int i;
if(bellman_ford(S))
fprintf(g,"Ciclu negativ!");
else
for(i=2;i<=N;++i)
fprintf(g,"%d ",d[i]);
fclose(g);
return 0;
}