Pagini recente » Cod sursa (job #1623555) | Cod sursa (job #3223843) | Cod sursa (job #471745) | Cod sursa (job #1234678) | Cod sursa (job #2482465)
#include <fstream>
#include <vector>
#include <queue>
#include <tuple>
using namespace std;
using VB = vector<bool>;
using VI = vector<int>;
using PI = pair<int, int>;
using VPI = vector<PI>;
using VVPI = vector<VPI>;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int inf = 0x3f3f3f3f;
VVPI G;
VI D, R;
VB inQ;
int n, m;
void Citire();
void BellmanFord(int);
void Afisare();
int main()
{
Citire();
BellmanFord(1);
Afisare();
}
void Citire()
{
in >> n >> m;
G = VVPI(n + 1);
for (int i = 1; i <= m; ++i)
{
int x, y, w;
in >> x >> y >> w;
G[x].emplace_back(w, y);
}
}
void BellmanFord(int sursa)
{
D = VI(n + 1, inf);
R = VI(n + 1);
queue<int> Q;
VB inQ = VB(n + 1);
D[sursa] = 0;
Q.push(sursa);
inQ[sursa] = true;
bool cNeg = false;
while (!cNeg && !Q.empty())
{
int x = Q.front();
Q.pop();
inQ[x] = false;
for (auto& p : G[x])
{
int y, dist_y;
tie(dist_y, y) = p;
if (D[y] > D[x] + dist_y)
{
D[y] = D[x] + dist_y;
if (!inQ[y])
Q.push(y), inQ[y] = true;
++R[x];
if (R[x] >= n)
{
D[0] = -1;
cNeg = true;
break;
}
}
}
}
}
void Afisare()
{
if (D[0] == -1)
out << "Ciclu negativ!";
else
for (int i = 2; i <= n; ++i)
out << D[i] << ' ';
}