Pagini recente » Cod sursa (job #973546) | Cod sursa (job #2390480) | Cod sursa (job #1356956) | Cod sursa (job #1982207) | Cod sursa (job #2840307)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int cost[50005],n,m,i,j,u,v,c,vis[50005],viz[50005];
bool in[50005];
vector<pair<int,int> >g[50005];
queue<int> q;
bool bellmanford()
{
fin>>n>>m;
for(int i=1;i<=m;i++)
{
fin>>u>>v>>c;
g[u].push_back({v,c});
}
for(int i=2;i<=n;i++)
cost[i]=(1<<30);
q.push(1);
in[1]=1;
viz[1]=1;
while(!q.empty())
{
int nod=q.front();
in[nod]=0;
vis[nod]++;
q.pop();
if(vis[nod]>=n)return 0;
for(auto it:g[nod])
if(cost[nod]+it.second<cost[it.first])
{
if(!in[it.first])
{
in[it.first]=1;
q.push(it.first);
}
cost[it.first]=cost[nod]+it.second;
}
}
return 1;
}
int main()
{
if(bellmanford())
{
for(int i=2;i<=n;i++)
fout<<cost[i]<<' ';
return 0;
}
fout<<"Ciclu negativ!";
return 0;
}