Pagini recente » Profil razvanflorin | Cod sursa (job #551314) | Istoria paginii utilizator/daria.dulgheru | Cod sursa (job #1172456) | Cod sursa (job #1790740)
#include <bits/stdc++.h>
using namespace std;
vector<vector<pair<int,int>>> G;
int N, M, dp[666013], used[666013];
queue<int> Q;
bitset<666013>inQ;
bool bellmanFord(int k)
{
Q.push(k);
inQ[k] = 1;
used[k] = 1;
memset(dp, 0x3f3f3f3f, sizeof(dp));
dp[k] = 0;
while(!Q.empty()) {
k = Q.front(); Q.pop();
inQ[k] = false;
for(auto it : G[k])
if(dp[it.second] > dp[k] + it.first) {
dp[it.second] = dp[k] + it.first;
if(inQ[it.second])
continue;
inQ[it.second] = true;
Q.push(it.second);
++used[it.second];
if(used[it.second] > N)
return true;
}
}
return false;
}
int main()
{
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
cin.sync_with_stdio(false);
cin >> N >> M;
G.resize(N + 1);
for(int i = 1; i <= M; ++i) {
int a,b,c;
cin >> a >> b >> c;
G[a].emplace_back(c,b);
}
bool ciclu = bellmanFord(1);
if(ciclu == true)
cout << "Ciclu negativ!";
else
for(int i = 2; i <= N; ++i)
cout << dp[i] << " ";
return 0;
}