Pagini recente » Cod sursa (job #102846) | Cod sursa (job #2414489) | Cod sursa (job #282698) | Cod sursa (job #3030314) | Cod sursa (job #3226965)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int M=250001,N=50001;
const int INF=1e9;
struct ura{
int x,y,c;
} v[M];
priority_queue<pair<int,int> >pq;
int vcost[N],vcnt[N];
bool vc[N];
vector<pair<int,int> >a[N];
int main()
{
int n,m,i,nod,nod2,cost;
fin>>n>>m;
for(i=1;i<=m;i++){
fin>>v[i].x>>v[i].y>>v[i].c;
a[v[i].x].push_back({v[i].y,v[i].c});
}
for(i=1;i<=N;i++)
vcost[i]=INF;
vcost[1]=0;
pq.push({0,1});
vcnt[1]=1;
while(!pq.empty())
{
nod=pq.top().second;
pq.pop();
vc[nod]=0;
for(auto p:a[nod])
{
cost=p.second;
nod2=p.first;
if(vcost[nod]+cost<vcost[nod2])
{
vcost[nod2]=vcost[nod]+cost;
if(!vc[nod2])
{
vc[nod2]=1;
vcnt[nod2]++;
pq.push({-vcost[nod2],nod2});
if(vcnt[nod2]>n)
{
fout<<"Ciclu negativ!";
return 0;
}
}
}
}
}
for(i=1;i<=m;i++)
{
if(vcost[v[i].x]+v[i].c<vcost[v[i].y])
{
fout<<"Ciclu negativ!";
return 0;
}
}
for(i=2;i<=n;i++)
fout<<vcost[i]<<' ';
return 0;
}