Pagini recente » Cod sursa (job #1073730) | Cod sursa (job #1010781) | Cod sursa (job #1968281) | Cod sursa (job #2373280) | Cod sursa (job #2718341)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
const int N = 50001;
const int INF = 1e9;
vector <pair <int, int>> a[N];
queue <int> q;
int n, d[N], nrq[N];
bool inq[N];
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
int main()
{
int m;
in >> n >> m;
for (int i = 0; i < m; i++)
{
int x, y, c;
in >> x >> y >> c;
a[x].push_back({y, c});
}
in.close();
//initializez d:
for (int i = 2; i <= n; i++)
{
d[i] = INF;
}
q.push(1);
d[1] = 0;
inq[1] = true;
nrq[1]++;
while (!q.empty())
{
//scot din q:
int x = q.front();
q.pop();
inq[x] = false;
//parcurg succesorii lui x:
for (auto p: a[x])
{
int y = p.first;
int c = p.second;
if (d[x] + c < d[y])
{
d[y] = d[x] + c;
if (!inq[y])
{
q.push(y);
nrq[y]++;
inq[y] = true;
if (nrq[y] == n)
{
out << "Ciclu negativ!";
out.close();
return 0;
}
}
}
}
}
for (int i = 2; i <= n; i++)
{
if (d[i] != INF)
{
out << d[i] << " ";
}
else
{
out << "0 ";
}
}
out.close();
return 0;
}