Pagini recente » Cod sursa (job #2177627) | Cod sursa (job #2808867) | Cod sursa (job #2709648) | Cod sursa (job #1654728) | Cod sursa (job #3349452)
#include <bits/stdc++.h>
#define nmax 50005
#define inf 50000005
using namespace std;
ifstream f("bellmanford.in");
ofstream g("bellmanford.out");
string mesaj="Ciclu negativ!";
int n,m,cost[nmax],fr[nmax];
vector<pair<int,int>> adj[nmax];///nod,cost
queue<int> Q;///noduri care s-au imbunatatit la pasul anterior
int main()
{
f>>n>>m;
for(int i=1;i<=m;i++)
{
int x,y,c;
f>>x>>y>>c;
adj[x].push_back({y,c});
}
for(int i=1;i<=n;i++)
{
cost[i]=inf;
}
cost[1]=0;
Q.push(1);
while(!Q.empty())
{
int nod=Q.front();
fr[nod]++;
if(fr[nod]==n)
{
g<<mesaj;
return 0;
}
Q.pop();
for(auto it:adj[nod])
{
int copil=it.first;
int cost_copil=it.second;
if(cost[nod]+cost_copil<cost[copil])
{
cost[copil]=cost[nod]+cost_copil;
Q.push(copil);
}
}
}
for(int i=2;i<=n;i++)
{
g<<cost[i]<<" ";
}
}