Pagini recente » Cod sursa (job #855821) | Cod sursa (job #2259637) | Cod sursa (job #425570) | Cod sursa (job #2651176) | Cod sursa (job #2557329)
#include <bits/stdc++.h>
#define pb push_back
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int MAXN = 50005, INF = 0x3f3f3f3f;
int dist[MAXN], vis[MAXN], n, m;
vector<pair<int, int>> graph[MAXN];
queue<int> q;
void read()
{
fin >> n >> m;
for (int i = 0; i < m; ++i) {
int x, y, c;
fin >> x >> y >> c;
graph[x].pb({y, c});
}
}
void init()
{
for (int i = 1; i <= n; ++i)
dist[i] = INF;
}
bool bf()
{
dist[1] = 0;
q.push(1);
while (!q.empty()) {
int node = q.front();
q.pop();
++vis[node];
if (vis[node] == n)
return false;
for (const auto& it: graph[node])
if (dist[it.first] > dist[node] + it.second) {
dist[it.first] = dist[node] + it.second;
q.push(it.first);
}
}
return true;
}
void print()
{
for (int i = 2; i <= n; ++i)
fout << dist[i] << ' ';
}
int main()
{
read();
init();
if (bf() == true)
print();
else
fout << "Ciclu negativ!";
return 0;
}