Pagini recente » Clasament 123456789101111111 | Cod sursa (job #2637330) | Cod sursa (job #2847987) | Cod sursa (job #2660668) | Cod sursa (job #2750204)
#include <bits/stdc++.h>
using namespace std;
const int kNmax = 100005;
class Task {
public:
void solve() {
read_input();
get_result();
}
private:
int n;
int m;
vector<pair<int, int>> adj[kNmax];
int source;
void read_input() {
ifstream fin("bellmanford.in");
fin >> n >> m;
for (int i = 1, x, y, c; i <= m; i++) {
fin >> x >> y >> c;
adj[x].push_back(make_pair(y, c));
}
//fin >> source;
fin.close();
}
void get_result() {
vector<int> distances(n + 1, INT_MAX);
vector<bool> flag(n + 1, false);
vector<int> count_in_queue(n + 1, 0);
source = 1;
queue<int> q;
q.push(source);
distances[source] = 0;
flag[source] = true;
bool negative_cycle = false;
while (!q.empty() && !negative_cycle) {
int node = q.front();
q.pop();
flag[node] = false;
for (auto &neigh_pair : adj[node]) {
int neigh = neigh_pair.first;
int edgeCost = neigh_pair.second;
if (distances[neigh] > distances[node] + edgeCost) {
distances[neigh] = distances[node] + edgeCost;
if (!flag[neigh]) {
if (count_in_queue[neigh] > n) {
negative_cycle = true;
break;
} else {
flag[neigh] = true;
q.push(neigh);
count_in_queue[neigh]++;
}
}
}
}
}
if (negative_cycle) {
ofstream fout("bellmanford.out");
fout << "Ciclu negativ!\n";
fout.close();
} else {
print_output(distances);
}
}
void print_output(vector<int> distances) {
ofstream fout("bellmanford.out");
for (int i = 2; i <= n; i++) {
int d = distances[i];
if (d == INT_MAX) {
fout << "-1 ";
} else {
fout << d << " ";
}
}
fout.close();
}
};
int main() {
Task *task = new Task();
task->solve();
delete task;
return 0;
}