Pagini recente » Cod sursa (job #2521921) | Cod sursa (job #1190090) | Cod sursa (job #2938145) | Cod sursa (job #1331302) | Cod sursa (job #3213879)
#include <bits/stdc++.h>
#include <unordered_map>
#define nmax 50006
#define MOD 1999999973
#define INF 2012345678
#define ll long long
using namespace std;
//#define fin cin
//#define fout cout
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
vector <pair <int, int>> L[nmax];
queue <int> q;
int cnt[nmax], d[nmax];
bitset <nmax> viz;
bool BellmanFord(int k)
{
int i, x, cost;
for (i = 1; i <= n; i++)
d[i] = INF;
d[k] = 0;
q.push(k);
cnt[k]++;
while (!q.empty())
{
k = q.front();
q.pop();
viz[k] = 0;
for (auto w : L[k])
{
x = w.second;
cost = w.first;
if (d[x] > d[k] + cost)
{
d[x] = d[k] + cost;
if (viz[x] == 0)
{
viz[x] = 1;
q.push(x);
cnt[x]++;
if (cnt[x] > n)
return 1;
}
}
}
}
return 0;
}
int main()
{
int i, x, y, c;
fin >> n >> m;
for (i = 1; i <= m; i++)
{
fin >> x >> y >> c;
L[x].push_back({ c, y });
}
if (BellmanFord(1))
fout << "Ciclu negativ!";
else
for (i = 2; i <= n; i++)
fout << d[i] << " ";
fout << "\n";
fin.close();
fout.close();
return 0;
}