Pagini recente » Cod sursa (job #2316191) | Cod sursa (job #1665494) | Cod sursa (job #1644424) | Cod sursa (job #3146150) | Cod sursa (job #3260508)
#include <bits/stdc++.h>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
const int Max = 5e4 + 1;
vector<pair<int,int>> graph[Max];
vector<int> d(Max, INT_MAX), c(Max);
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>>> q;
void bellman_ford(int node)
{
q.push({0, node});
d[node] = 0;
while(!q.empty())
{
node = q.top().second;
q.pop();
for(auto const& i: graph[node])
{
int neighbour = i.first;
int cost = i.second;
if(d[node] + cost < d[neighbour])
{
d[neighbour] = d[node] + cost;
q.push({d[neighbour], neighbour});
if(++c[neighbour] == n)
{
fout << "Ciclu negativ!";
return;
}
}
}
}
for(int i = 2; i <= n; ++i)
{
fout << d[i] << " ";
}
}
int main()
{
ios::sync_with_stdio(false);
fin.tie(NULL);
int x, y, z;
fin >> n >> m;
for(int i = 1; i <= m; ++i)
{
fin >> x >> y >> z;
graph[x].push_back({y, z});
}
bellman_ford(1);
fin.close();
fout.close();
return 0;
}