Pagini recente » Cod sursa (job #2039331) | Borderou de evaluare (job #2041294) | Borderou de evaluare (job #1874621) | Borderou de evaluare (job #2202442) | Cod sursa (job #2801475)
#include <bits/stdc++.h>
#define _nod pair<int,int>
#pragma GCC optimize ("O3")
#pragma GCC optimize ("Ofast")
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
const int INF = 1e9;
const int maxN = 50005;
const int maxM = 250005;
int n, a, b, c;
vector <_nod> v[maxN];
bool ciclu = false;
priority_queue <_nod> q;
int viz[maxN], dp[maxN];
void belman_ford(int start){
for(int i=1; i<=n; i++)
dp[i] = INF;
dp[start] = 0;
int nod, nxt, cst;
q.push({0, start});
while(!q.empty()){
nod = q.top().second;
q.pop();
for(int i=0; i<(int)v[nod].size(); i++){
nxt = v[nod][i].first;
cst = v[nod][i].second;
if(dp[nxt] > dp[nod] + cst){
dp[nxt] = dp[nod] + cst;
viz[nxt]++;
if(viz[nxt] > n){
ciclu=true;
fout<<"Ciclu negativ!";
return;
}
q.push({-dp[nxt], nxt});
}
}
}
}
int main (){
ios_base::sync_with_stdio(false); fin.tie(0); fout.tie(0);
fin>>n;
int edgeCnt; fin>>edgeCnt;
while(edgeCnt--){
fin>>a>>b>>c;
v[a].push_back({b, c});
}
belman_ford(1);
if(ciclu == true)
return 0;
for(int i=2; i<=n; i++)
fout<<dp[i]<<" ";
return 0;
}