Pagini recente » Cod sursa (job #491367) | Cod sursa (job #1759860) | Cod sursa (job #477643) | Cod sursa (job #1893334) | Cod sursa (job #3284985)
#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
vector<pair<int, int>> adj[NMAX + 1];
bool inQ[NMAX + 1];//sa stou daca e in coada
bool e_ciclu;
queue<int> q;
int n, m;
void belly(int nod){
dist[nod] = 0;
inQ[nod] = true;
cntQ[nod] = 1;
q.push(nod);
while(!q.empty()){
int fromnod = q.front();
q.pop();
inQ[fromnod] = false;//nu mai e in coada gen
if(cntQ[nod] >= n){
e_ciclu = true;
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});
}
for(int i=1; i<=n; i++)
dist[i] = 2e9;
belly(1);
if(e_ciclu){
g << "Ciclu negativ!";
return 0;
}
for(int i=2; i<=n; i++)
g << dist[i] << ' ';
return 0;
}