Pagini recente » Cod sursa (job #2010859) | Cod sursa (job #1256012) | Cod sursa (job #2672786) | Cod sursa (job #2283500) | Cod sursa (job #2071660)
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
using VI = vector<int>;
using VB = vector<bool>;
using VP = vector<pair<int, int>>;
const int Inf = 0x3f3f3f3f;
int n, m;
VI d, N;
VB inQ;
vector<VP> G;
bool ok;
void ReadGraph();
void BellmanFord(int x, VI& d);
int main()
{
ReadGraph();
BellmanFord(1, d);
if (!ok)
for (int i = 2; i <= n; i++)
fout << d[i] << ' ';
else
fout << "Ciclu negativ!";
fin.close();
fout.close();
}
void BellmanFord(int x, VI& d)
{
d = VI(n + 1, Inf);
N = VI(n + 1);
inQ = VB(n + 1);
queue<int> Q;
d[x] = 0;
Q.push(x);
N[x]++;
inQ[x] = true;
int y, w;
while (!Q.empty())
{
x = Q.front();
Q.pop();
for (const auto& p : G[x])
{
y = p.first;
w = p.second;
if (d[y] > d[x] + w)
{
d[y] = d[x] + w;
if ( !inQ[y] )
{
Q.push(y);
N[y]++;
inQ[y] = true;
if (N[y] == n)
{
ok = true;
return;
}
}
}
}
}
}
void ReadGraph()
{
fin >> n >> m;
G = vector<VP>(n + 1);
int x, y, w;
while (m--)
{
fin >> x >> y >> w;
G[x].push_back({y, w});
}
}