Pagini recente » Cod sursa (job #2792216) | Cod sursa (job #2334918) | Cod sursa (job #1484355) | Cod sursa (job #1395072) | Cod sursa (job #2988972)
#include <iostream>
#include <fstream>
#include <vector>
#include <stack>
#include <queue>
using namespace std;
ifstream f("bellmanford.in");
ofstream g ("bellmanford.out");
vector<pair<int,int>>adiacenta[50001];
priority_queue<pair<int,int>, vector<pair<int,int>>, greater<pair<int,int>> >q;
int cnt[50001];
bool viz[50001];
int dist[50001];
int n,m;
void citire()
{
f >> n >> m;
for(int i = 1;i<=m;i++)
{
int x,y,c;
f >> x>> y >> c;
adiacenta[x].push_back({y,c});
}
}
void init()
{
for(int i = 1;i<=50001;i++)
dist[i]=1<<30-1;
}
int main()
{
init();
citire();
q.push({0,1});
while(!q.empty())
{
int curent = q.top().second;
int cost = q.top().first;
q.pop();
if(viz[curent]==1)
continue;
viz[curent] = 1;
cnt[curent]++;
if(cnt[curent]>n)
{
g << "Ciclu negativ!";
return 0;
}
for(auto x:adiacenta[curent])
{
if(dist[x.first]>cost+x.second)
{
dist[x.first]= cost+x.second;
q.push({dist[x.first],x.first});
}
}
}
for(int i=2;i<=n;i++)
g << dist[i]<< " ";
}