Pagini recente » Cod sursa (job #3265276) | Cod sursa (job #565344) | Cod sursa (job #70267) | Cod sursa (job #887164) | Cod sursa (job #3165115)
#include <iostream>
#include <fstream>
#include <queue>
#include <vector>
#define ll long long
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const ll NMAX = 50003, INF = 1e14;
int n, m;
ll d[NMAX], inQ[NMAX];
bool vis[NMAX];
vector<pair<ll, ll> > g[NMAX];
bool ford(ll s) {
for (int i = 1; i <= n; i++) {
d[i] = INF;
}
d[s] = 0;
queue<ll> q;
q.push(s);
bool negativ = false;
while (!q.empty() && !negativ) {
ll curr = q.front();
q.pop();
vis[curr] = false;
for (auto nxt : g[curr]) {
ll nod = nxt.first, cost = nxt.second;
if (d[nod] > d[curr] + cost) {
d[nod] = d[curr] + cost;
if (!vis[nod]) {
inQ[nod]++;
if (inQ[nod] > n) {
negativ = true;
break;
}
vis[nod] = true;
q.push(nod);
}
}
}
}
return !negativ;
}
int main() {
fin >> n >> m;
for (int i = 1; i <= m; i++) {
ll x, y, cost;
fin >> x >> y >> cost;
g[x].push_back(make_pair(y, cost));
}
if (ford(1)) {
for (int i = 2; i <= n; i++) {
fout << d[i] << ' ';
}
} else {
fout << "Ciclu negativ!";
}
return 0;
}