Pagini recente » Cod sursa (job #1128340) | Uită-te jos, nu în bara de titlu! | Cod sursa (job #2546543) | Cod sursa (job #1382284) | Cod sursa (job #2197798)
#include <bits/stdc++.h>
#define inf 100000000
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector <pair<int, int> > L[50005];
priority_queue <int> q;
int n, p, drum[50005], m, frecv[50005];
bool viz[50005];
void Citire()
{
int x, y, c;
fin >> n >> m;
while(fin >> x >> y >> c)
{
L[x].push_back({y,c});
}
}
void Dijkstra()
{
q.push(1);
for(int i = 1; i <= n; i++)
drum[i] = inf;
drum[1] = 0;
viz[1] = true;
bool ciclu = false;
while(!q.empty() && ciclu == false)
{
int el = q.top();
q.pop();
for(auto i : L[el])
{
int nod = i.first;
int cost = i.second;
if(drum[nod] > drum[el] + cost)
{
drum[nod] = drum[el] + cost;
if(!viz[nod])
{
viz[nod] = 1;
if(++frecv[nod] > n) ciclu = true;
q.push(nod);
}
}
}
}
if(ciclu)
fout << "Ciclu negativ!\n";
else for(int i = 2; i <= n; i++)
fout << drum[i] << " ";
}
int main()
{
Citire();
Dijkstra();
return 0;
}