Pagini recente » Cod sursa (job #2512665) | Cod sursa (job #311674) | Cod sursa (job #964357) | Cod sursa (job #2622594) | Cod sursa (job #2663806)
#include <bits/stdc++.h>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
int oo=2000000009;
vector < pair < int , int > > v[50005];
queue < int > q;
int viz[50005];
int dist[50005];
int n,m,x,y,d;
int ok=1;
bool 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;
if (viz[nod]>=n) {
ok=0;
}
else {
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;
}