Pagini recente » Cod sursa (job #1213387) | Cod sursa (job #1214311) | Cod sursa (job #2472939) | Cod sursa (job #1710106) | Cod sursa (job #2655221)
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
using PI = pair<int, int>;
using VP = vector<PI>;
using VVP = vector<VP>;
using VI = vector<int>;
using VB = vector<bool>;
const int Inf = 0x3f3f3f3f;
int n, m;
VVP G;
VI d;
void Read();
bool BellmanFord(int x, VI& d);
int main()
{
Read();
ofstream fout("bellmanford.out");
if (BellmanFord(1, d))
fout << "Ciclu negativ!";
else
for (int i = 2; i <= n; i++)
fout << d[i] << ' ';
}
bool BellmanFord(int x, VI& d)
{
d = VI(n + 1, Inf);
d[x] = 0;
for (int i = 1; i < n; i++)
for (int x = 1; x <= n; x++)
for (const PI& p : G[x])
{
int y = p.first;
int w = p.second;
if (d[y] > d[x] + w)
d[y] = d[x] + w;
}
for (int x = 1; x <= n; x++)
for (const PI& p : G[x])
{
int y = p.first;
int w = p.second;
if (d[y] > d[x] + w)
return true;
}
return false;
}
void Read()
{
ifstream fin("bellmanford.in");
fin >> n >> m;
G = VVP(n + 1);
int x, y, w;
for (int i = 0; i < m; i++)
{
fin >> x >> y >> w;
G[x].emplace_back(y, w);
}
}