Pagini recente » Cod sursa (job #1891149) | Cod sursa (job #946742) | Cod sursa (job #3277255) | Cod sursa (job #2504524) | Cod sursa (job #3285007)
#include <bits/stdc++.h>
using namespace std;
ifstream f ("bellmanford.in");
ofstream g ("bellmanford.out");
const int NMAX = 5e4;
int dist[NMAX + 1], cntQ[NMAX + 1];//sa stiu de cate ori a aparurt nodul in coada maxim n-1 ori pt solutie fara ciclu de cost negativ
struct ura{
int first, second;
};
vector<ura> adj[NMAX + 1];
bool inQ[NMAX + 1];//sa stou daca e in coada
bool e_ciclu = true;
queue<int> q;
int n, m;
void belly(int nod){
q.push(nod);
dist[nod] = 0;
while(!q.empty()){
int fromnod = q.front();
q.pop();
//cout << fromnod << endl;
inQ[fromnod] = false;//nu mai e in coada gen
if(cntQ[fromnod] >= n){
e_ciclu = false;
return;
}
for(auto next : adj[fromnod]){
int tonod = next.first;
int tocost = next.second;
if(dist[tonod] > dist[fromnod] + tocost){
dist[tonod] = dist[fromnod] + tocost;
if(!inQ[tonod])
inQ[tonod] = true, q.push(tonod);
cntQ[tonod] ++;
}
}
}
}
int main()
{
f.tie(NULL);
ios_base::sync_with_stdio(false);
f >> n >> m;
for(int i=1; i<=m; i++){
int x, y, cost;
f >> x >> y >> cost;
adj[x].push_back({y, cost});
}
fill(dist + 2, dist + 1 + NMAX, 2e9);
belly(1);
if(e_ciclu == false){
g << "Ciclu negativ!";
return 0;
}
for(int i=2; i<=n; i++)
g << dist[i] << ' ';
return 0;
}