Pagini recente » Cod sursa (job #1084161) | Cod sursa (job #2693848) | Cod sursa (job #1588324) | Cod sursa (job #2646174) | Cod sursa (job #2663792)
#include <bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int oo=2000000009;
queue < int > q;
vector < pair < int , int > > v[50005];
int dist[50005];
int n, m, x, y, d;
int ok=1;
int viz[50005];
int inqueue[50005];
int main()
{
f >> n >> m;
for (int i=1;i<=m;i++) {
f >> x >> y >> d;
v[x].push_back(make_pair(y,d));
}
for (int i=1;i<=n;i++) {
dist[i] = oo;
}
dist[1]=0;
q.push(1);
inqueue[1]=1;
while (q.empty()==0 && ok==1) {
int nod = q.front();
q.pop();
inqueue[nod]=0;
viz[nod]++;
for (int i=1;i<=n;i++) {
if (viz[i]>=n) {
ok=0;
}
}
for (int i=0; i<v[nod].size(); i++) {
int nodtoviz = v[nod][i].first;
int distance = v[nod][i].second;
if (dist[nodtoviz] > dist[nod] + distance) {
dist[nodtoviz] = dist[nod] + distance;
if (inqueue[nodtoviz]==0) {
q.push(nodtoviz);
inqueue[nodtoviz]=1;
}
}
}
}
if (ok==1) {
for (int i=2;i<=n;i++) {
g << dist[i]<<" ";
}
}
else {
g << "Ciclu negativ!";
}
return 0;
}