Pagini recente » Istoria paginii runda/zvzx | Cod sursa (job #2332870) | Cod sursa (job #2632532) | Cod sursa (job #2204551) | Cod sursa (job #2750199)
#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;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
pq.push(make_pair(0, source));
distances[source] = 0;
flag[source] = true;
bool negative_cycle = false;
while (!pq.empty() && !negative_cycle) {
pair<int, int> top = pq.top();
pq.pop();
int node = top.second;
int cost = top.first;
flag[node] = false;
for (auto &neigh_pair : adj[node]) {
int neigh = neigh_pair.first;
int edgeCost = neigh_pair.second;
if (distances[neigh] > cost + edgeCost) {
distances[neigh] = cost + edgeCost;
if (!flag[neigh]) {
if (count_in_queue[neigh] > n) {
negative_cycle = true;
break;
} else {
flag[neigh] = true;
pq.push(make_pair(distances[neigh], 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("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;
}