Pagini recente » Cod sursa (job #236590) | Cod sursa (job #1491008) | Cod sursa (job #2797573) | preONI 2008 | Cod sursa (job #2374686)
#include <fstream>
#include <vector>
#include <queue>
#include <algorithm>
using namespace std;
using PI = pair<int, int>;
using VP = vector<PI>;
using VI = vector<int>;
using VB = vector<bool>;
ofstream fout("bellmanford.out");
const int Inf = 0x3f3f3f3f;
int n, m;
vector<VP> G;
VI d, N;
queue<int> Q;
VB inQ;
void Read();
int main()
{
Read();
int x = 1;
d = VI(n + 1, Inf);
N = VI(n + 1);
inQ = VB(n + 1);
d[x] = 0;
Q.push(x);
inQ[x] = true;
N[x]++;
int y, w;
while (!Q.empty())
{
x = Q.front();
Q.pop();
inQ[x] = false;
for (const PI& 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);
inQ[y] = true;
N[y]++;
if (N[y] == n)
{
fout << "Ciclu negativ!";
return 0;
}
}
}
}
}
for (x = 2; x <= n; x++)
fout << d[x] << ' ';
fout.close();
}
void Read()
{
ifstream fin("bellmanford.in");
fin >> n >> m;
G = vector<VP>(n + 1);
int x, y, w;
for (int i = 0; i < m; i++)
{
fin >> x >> y >> w;
G[x].push_back({y, w});
}
fin.close();
}