Pagini recente » Cod sursa (job #1675352) | Cod sursa (job #1792906) | Cod sursa (job #1590659) | Cod sursa (job #511320) | Cod sursa (job #3265680)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
#include <algorithm>
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
struct ComparePairs
{
bool operator()(const pair<int, int> &p1, const pair<int, int> &p2)
{
return p1.second > p2.second;
}
};
void Read(vector<vector<pair<int, int>>> &adj, int m)
{
int x, y, c;
for (int i = 1; i <= m; i++)
{
f >> x >> y >> c;
adj[x].push_back(make_pair(y, c));
}
}
void BellmanFord(vector<vector<pair<int, int>>> &adj_matrix, vector<int> &distanta, int n)
{
queue<int> q;
vector<bool> in_q(n + 1);
vector<int> cnt_in_q(n + 1, 0);
q.push(1);
distanta[1] = 0;
in_q[1] = true;
while (!q.empty())
{
int nod_curent = q.front();
q.pop();
in_q[nod_curent] = false;
for (auto &vecin : adj_matrix[nod_curent])
{
int nod_vecin = vecin.first;
int cost = vecin.second;
if (distanta[nod_curent] < INT_MAX && distanta[nod_curent] + cost < distanta[nod_vecin])
{
distanta[nod_vecin] = distanta[nod_curent] + cost;
if (!in_q[nod_vecin])
{
if (cnt_in_q[nod_vecin] > n)
{
g << "Ciclu negativ!";
exit(0);
}
q.push(nod_vecin);
in_q[nod_vecin] = true;
cnt_in_q[nod_vecin]++;
}
}
}
}
for (int nod_curent = 1; nod_curent <= n; nod_curent++)
{
for (auto &vecin : adj_matrix[nod_curent])
{
int nod_vecin = vecin.first;
int cost = vecin.second;
if (distanta[nod_curent] + cost < distanta[nod_vecin])
{
g << "Ciclu negativ!";
exit(0);
}
}
}
}
int main()
{
int n, m;
f >> n >> m;
vector<vector<pair<int, int>>> adj(n + 1);
Read(adj, m);
vector<int> distanta(n + 1, INT_MAX);
BellmanFord(adj, distanta, n);
for (int i = 2; i <= n; i++)
{
g << distanta[i] << " ";
}
return 0;
}