Pagini recente » Cod sursa (job #83011) | Cod sursa (job #380362) | Cod sursa (job #837506) | Cod sursa (job #325004) | Cod sursa (job #1494813)
#include <cstdio>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
const int nmx = 50002, inf = 0x3f3f3f3f;
int n,m,dist[nmx],cnt[nmx];
vector <pair<int,int> > g[nmx];
queue <int> q;
int main(){
freopen("bellmanford.in", "r", stdin);
freopen("bellmanford.out", "w", stdout);
scanf("%d %d", &n, &m);
int nod1,nod2,cost;
for(int i = 1; i <= m; ++i){
scanf("%d %d %d", &nod1, &nod2, &cost);
g[nod1].push_back(make_pair(nod2,cost));
}
q.push(1);
memset(dist,inf,sizeof(dist));
dist[1] = 0;
while(not q.empty()){
int nod = q.front();
q.pop();
for(vector<pair<int,int> >::iterator it = g[nod].begin(); it != g[nod].end(); ++it)
if(dist[it->first] > dist[nod] + it->second){
++ cnt[it->first];
if(cnt[it->first] > n){
printf("Ciclu negativ!\n");
return 0;
}
dist[it->first] = dist[nod] + it->second;
q.push(it->first);
}
}
for(int i = 2; i <= n; ++i)
printf("%d ", dist[i]);
return 0;
}