Pagini recente » Cod sursa (job #2165399) | Cod sursa (job #817570) | Cod sursa (job #1199296) | Cod sursa (job #291459) | Cod sursa (job #2571942)
#include<bits/stdc++.h>
using namespace std;
int n,m;
const int maxN=(5e4)+5;
vector<pair<int,int> > v[maxN];
int dp[maxN],x,y,z;
deque<int> q;
bool inQueue[maxN];
int used[maxN];
int main()
{
freopen("bellmanford.in","r",stdin);
freopen("bellmanford.out","w",stdout);
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
v[x].push_back({y,z});
}
q.push_back(1);
used[1]=1;
inQueue[1]=1;
for(int i=2;i<=n;i++)
dp[i]=INT_MAX;
while(!q.empty())
{
int nod=q.front();
for(auto it:v[nod])
{
if(dp[it.first]>dp[nod]+it.second)
{
dp[it.first]=dp[nod]+it.second;
if(!inQueue[it.first])
{
q.push_back(it.first);
inQueue[it.first]=1;
}
used[it.first]++;
if(used[it.first]==(n+1))
{
printf("Ciclu negativ!\n");
return 0;
}
}
}
inQueue[nod]=0;
q.pop_front();
}
for(int i=2;i<=n;i++)
printf("%d ",dp[i]);
return 0;
}