Pagini recente » Cod sursa (job #1122164) | Cod sursa (job #2350982) | Cod sursa (job #1534504) | Cod sursa (job #2923727) | Cod sursa (job #2490919)
#include <cstdio>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
int n,m,nod,lungime,vizitat[50003],grad[50003],cost[50003];bool ok;
vector < pair <int,int> > graf[50003];
queue < pair <int,int> > chestie;
void bellman_ford () {
while(chestie.size()!=0) {
nod=chestie.front().first;
lungime=chestie.front().second;
for(int i=0;i<(int)graf[nod].size();++i)
if(vizitat[graf[nod][i].first]<(n-1)*grad[graf[nod][i].first]) {
++vizitat[graf[nod][i].first];
if(cost[graf[nod][i].first]>cost[nod]+graf[nod][i].second)
cost[graf[nod][i].first]=cost[nod]+graf[nod][i].second;
chestie.push(make_pair(graf[nod][i].first,cost[graf[nod][i].first]));
}
else
if(cost[graf[nod][i].first]>cost[nod]+graf[nod][i].second){
printf("Ciclu negativ!");ok=false;
return ;
}
chestie.pop();
}
}
int main () {
int nr1,nr2,nr3;
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
scanf("%d%d", &n, &m);
for(int i=1;i<=m;++i) {
scanf("%d%d%d", &nr1, &nr2, &nr3);
graf[nr1].push_back(make_pair(nr2,nr3));
grad[nr2]++;
}
for(int i=2;i<=n;++i)
cost[i]=1e9;
ok=true;
chestie.push(make_pair(1,0));
bellman_ford();
if(ok==true)
for(int i=2;i<=n;++i)
printf("%d ", cost[i]);
return 0;
}