Pagini recente » Cod sursa (job #1738758) | Cod sursa (job #1997842) | Cod sursa (job #2769070) | Cod sursa (job #102986) | Cod sursa (job #442032)
Cod sursa(job #442032)
#include <cstdio>
#include <vector>
#include <bitset>
using namespace std;
#define INF 0x3f3f3f3f
#define MAXN 50005
#define MAXM 250005
typedef vector<pair<int,int> >::iterator iter;
vector<pair<int,int> > g[MAXN];
bitset<MAXN> inList;
int n,m,cn=0,d[MAXN],list[MAXN],cycle[MAXN],lp=0;
inline bool bellmanford(){
bool neg=false;
int top;
for(int i=2;i<=n;i++){
d[i]=INF;
}
d[1]=0,list[++lp]=1,inList[1]=true;
while(lp>0&&!neg){
top=list[lp--];
inList[top]=false;
for(iter it=g[top].begin();it!=g[top].end();it++){
if(dist[top]<INF){
if(d[it->first]>d[top]+it->second){
d[it->first]=d[top]+it->second;
if(!inList[it->first]){
if(cycle[it->first]>n){
neg=true;
}else{
list[++lp]=it->first,inList[it->first]=true,cycle[it->first]++;
}
}
}
}
}
}
return !neg;
}
int main(){
int x,y,c;
FILE* fin=fopen("bellmanford.in","r");
FILE* fout=fopen("bellmanford.out","w");
fscanf(fin,"%d %d\n",&n,&m);
for(int i=0;i<m;i++){
fscanf(fin,"%d %d %d\n",&x,&y,&c);
g[x].push_back(make_pair(y,c));
}
if(!bellmanford()){
fprintf(fout,"Ciclu negativ!\n");
}else{
for(int i=2;i<=n;i++){
fprintf(fout,"%d ",(d[i]==INF)?0:d[i]);
}
}
fclose(fin);
fclose(fout);
return 0;
}