Pagini recente » Monitorul de evaluare | Monitorul de evaluare | Monitorul de evaluare | Cod sursa (job #2198415) | Cod sursa (job #2198424)
#include <fstream>
#include <vector>
#include <queue>
#define INF (1 << 30)
using namespace std;
int main() {
int N, M, A, B, C;
int d[50001];
d[1] = 0;
ifstream in("bellmanford.in");
ofstream out ("bellmanford.out");
in >> N >> M;
vector<pair<int, int>> graph[50001];
for (int i = 0; i < M; i++) {
in >> A >> B >> C;
graph[A].push_back(make_pair(B, C));
}
vector<int> check(N + 1, 0);
queue<int> q;
q.push(1);
while (!q.empty()) {
int node = q.front();
q.pop();
for (pair<int, int> n : graph[node]) {
int node = n.first;
int dist = n.second;
if (d[node] > d[node] + dist) {
d[node] = d[node] + dist;
q.push(node);
check[node]++;
if (check[node] == N) {
out << "Ciclu negativ!";
return 0;
}
}
}
}
for (int i = 2 ; i <= N; i++) {
if (d[i] == INF) {
out << 0 << " ";
} else {
out << d[i] << " ";
}
}
out.close();
in.close();
return 0;
}