Pagini recente » Cod sursa (job #305846) | Cod sursa (job #2283391) | Cod sursa (job #201174) | Documentatie | Cod sursa (job #2765744)
#include <bits/stdc++.h>
#define ll long long
#define nl '\n'
#define FOR(i, a, b) for (int i = a; i <= b; ++i)
#define F0R(i, a, b) for (int i = a; i >= b; --i)
#define FORd(i, n) for (int i = 0; i < n; ++i)
#define F0Rd(i, n) for (int i = n - 1; i >= 0; --i)
#define trav(a, x) for (auto &a : x)
#define uid(a, b) uniform_int_distribution<int>(a, b)(rng)
using namespace std;
mt19937 rng(chrono::steady_clock::now().time_since_epoch().count());
const int mxN = 1e5 + 5, INF = 1e9 + 7;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int N, M, dist[mxN], cnt_in_queue[mxN];
vector<pair<int, int>> edges[mxN];
bitset<mxN> inQueue;
void BF() {
queue<int> q;
q.push(1);
dist[1] = 0;
while (q.size()) {
int node = q.front();
q.pop();
inQueue[node] = false;
for (pair<int, int> elem : edges[node]) {
int next_node = elem.first;
int new_cost = elem.second;
if (dist[next_node] > dist[node] + new_cost) {
dist[next_node] = dist[node] + new_cost;
if (cnt_in_queue[next_node] > N) {
fout << "Ciclu negativ!";
return;
}
q.push(next_node);
inQueue[next_node] = true;
cnt_in_queue[next_node]++;
}
}
}
for (int i = 2; i <= N; ++i) {
fout << dist[i] << " ";
}
}
void solve() {
fin >> N >> M;
for (int i = 1; i <= N; ++i) {
dist[i] = INF;
}
while (M--) {
int x, y, z;
fin >> x >> y >> z;
edges[x].push_back({y, z});
}
BF();
}
int main() {
fin.tie(0); fout.tie(0);
ios::sync_with_stdio(0);
int T = 1;
// cin >> T;
while (T--) {
solve();
}
return 0;
}
//read the question correctly (ll vs int)
//what's the meaning of the problem ? Think outside the BOX !!!
//edge cases ?
//make it simple
//write everything (observations, edge cases, ideas, steps, methods, ...)