Pagini recente » Cod sursa (job #2693542) | Cod sursa (job #226139) | Cod sursa (job #525537) | Cod sursa (job #370803) | Cod sursa (job #3286371)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <vector>
#include <tuple>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
using VI = vector<int>;
using VPI = vector<pair<int, int>>;
using VVPI = vector<VPI>;
using VVI = vector<VI>;
using VB = vector<bool>;
int n, m;
const int INF = (1 << 30);
VVPI G;
VI v;
VI d;
bool cicluNegativ;
void BellmanFord(int x)
{
queue<int> Q;
VB inQ(n + 1);
VI cnt(n + 1);
Q.emplace(x);
inQ[x] = true;
d[x] = 0;
while(!Q.empty())
{
x = Q.front();
inQ[x] = false;
Q.pop();
for (auto& y : G[x])
{
if (d[y.second] > y.first + d[x])
{
d[y.second] = y.first + d[x];
if (!inQ[y.second])
{
inQ[y.second] = true;
Q.emplace(y.second);
}
cnt[y.second]++;
if (cnt[y.second] > n)
{
cicluNegativ = true;
return;
}
}
}
}
}
int main()
{
fin >> n >> m;
G = VVPI(n + 1);
d = VI(n + 1, INF);
int x, y, w;
for (int i = 1; i <= m; ++i)
{
fin >> x >> y >> w;
G[x].emplace_back(w, y);
}
BellmanFord(1);
if (!cicluNegativ)
for (int i = 2; i <= n; ++i)
fout << d[i] << ' ';
else
fout << "Ciclu negativ!";
}