Pagini recente » Cod sursa (job #3337157) | Cod sursa (job #3124863) | Cod sursa (job #530736) | Cod sursa (job #141786) | Cod sursa (job #3344511)
#include <bits/stdc++.h>
std::ifstream fin("bellmanford.in");
std::ofstream fout("bellmanford.out");
struct nod
{
int node;
int cost;
};
int countt[50005];
int dist[50005];
int in_queue[50005];
std::vector<std::vector<nod>> g;
int main()
{
std::ios_base::sync_with_stdio(false);
fin.tie(nullptr);
int n, m;
fin >> n >> m;
g.resize(n + 1);
for(int i = 1; i <= m; i++)
{
dist[i] = INT_MAX;
int a, b, cost;
fin >> a >> b >> cost;
g[a].push_back({b, cost});
}
std::queue<int> q;
q.push(1);
dist[1] = 0;
while(!q.empty())
{
int nod = q.front();
q.pop();
in_queue[nod] = false;
for(auto leg : g[nod])
{
int neigh = leg.node;
int cost = leg.cost;
if(dist[neigh] > dist[nod] + cost)
{
dist[neigh] = dist[nod] + cost;
if(in_queue[neigh] == false)
{
q.push(neigh);
in_queue[neigh] = true;
countt[neigh]++;
if(countt[neigh] >= n)
{
fout << "Ciclu negativ!";
return 0;
}
}
}
}
}
for(int i = 2; i <= n; i ++)
fout << dist[i] << ' ';
return 0;
}