Pagini recente » Rezultatele filtrării | Cod sursa (job #2843925)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const unsigned nmax = 50005;
struct edge{
int i;
int j;
int cost;
edge(int _i, int _j, int _cost): i(_i), j(_j), cost(_cost) {}
};
int main()
{
int N, M;
vector<pair<int, int>> adj[nmax];
queue<int> q;
bool inQ[nmax] = {false};
int distMin[nmax];
int cnt[nmax] = {0};
fin >> N >> M;
for(int i = 1; i <= M; ++i){
int src, dst, cost;
fin >> src >> dst >> cost;
adj[src].push_back(make_pair(dst, cost));
}
distMin[1] = 0;
for(int i = 2; i <= N; ++i)
distMin[i] = INT_MAX / 2;
q.push(1);
inQ[1] = true;
while(!(q.empty())){
int i = q.front();
q.pop();
inQ[i] = false;
for(auto vecin: adj[i]){
int j = vecin.first;
int cost = vecin.second;
if(distMin[i] + cost < distMin[j]){
distMin[j] = distMin[i] + cost;
if(inQ[j] == false)
{ q.push(j);
inQ[j] = true;
++cnt[j];
if(cnt[j] >= N - 1)
{
fout << "Ciclu negativ!\n";
return 0;
}
}
}
}
}
for(int i = 2; i <= N; ++i)
fout << distMin[i] << ' ';
return 0;
}