Pagini recente » Cod sursa (job #2064795) | Cod sursa (job #1697897) | Cod sursa (job #1457761) | Cod sursa (job #1394262) | Cod sursa (job #1264778)
#include <fstream>
#include <list>
#include <queue>
#include <bitset>
#define DIM 50011
#define INF 25000011
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int n,m,ng,nr;
int D[DIM],U[DIM];
list<pair<int,int> > L[DIM];
queue<int> q;
bitset<DIM> viz;
int main(void){
register int i,j,x,y,c,nod;
list<pair<int,int> >::iterator it;
f>>n>>m;
for(i=1;i<=m;i++){
f>>x>>y>>c;
L[x].push_back(make_pair(c,y));
}
for(i=2;i<=n;i++) D[i]=INF;
q.push(1);
while(!q.empty() && !ng){
nod=q.front(),q.pop();
for(it=L[nod].begin();it!=L[nod].end();it++){
if(D[it->second]>D[nod]+it->first){
U[it->second]++;
if(U[it->second]==n){
ng=1;
break;
}
D[it->second]=D[nod]+it->first;
if(!viz[it->second])
q.push(it->second),viz[it->second]=1;
}
}
}
if(ng)
g<<"Ciclu negativ!";
else
for(i=2;i<=n;i++) g<<D[i]<<" ";
f.close();
g.close();
return 0;
}