Pagini recente » Cod sursa (job #1892475) | Cod sursa (job #644399) | Cod sursa (job #2031373) | Cod sursa (job #2897251) | Cod sursa (job #3161046)
#include <bits/stdc++.h>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
typedef unsigned long long ull;
typedef long long ll;
typedef pair<int, int> pii;
#define fi first
#define se second
#define NMAX 50005
#define MOD 1000000007
#define INF 0x3f3f3f3f
vector<vector<pii>> graf(NMAX);
int n, ans, dist[NMAX], cnt[NMAX];
void read()
{
int x, y, wt, m;
in >> n >> m;
while (m--)
in >> x >> y >> wt, graf[x].emplace_back(y, wt);
}
void BellmanFord(int start)
{
memset(dist, INF, sizeof dist);
dist[start] = 0;
queue<pii> Q;
Q.push({start, 0});
while (!Q.empty())
{
int u, cost;
tie(u, cost) = Q.front();
Q.pop();
for (auto node : graf[u])
{
int to = node.fi, currcost = node.se;
if (cost + currcost < dist[to])
{
dist[to] = cost + currcost, Q.push({to, dist[to]});
cnt[to]++;
if (cnt[to] == n + 2)
{
out << "Ciclu negativ!";
exit(0);
}
}
}
}
}
void solve()
{
BellmanFord(1);
for (int i = 2; i <= n; i++)
out << dist[i] << ' ';
}
int main()
{
read();
solve();
return 0;
}