Pagini recente » Cod sursa (job #1675484) | Cod sursa (job #2267414) | Cod sursa (job #936919) | Cod sursa (job #2025283) | Cod sursa (job #2447573)
#include <bits/stdc++.h>
using namespace std;
ifstream inf("bellmanford.in");
ofstream outf("bellmanford.out");
const int N=50010, INF=500000000;
bool inq[N];
int tms[N], sol[N];
int n, m;
vector<pair<int,int>> v[N];
int main()
{
inf>>n>>m;
for(int i=1; i<=m; i++)
{
int x, y, z;
inf>>x>>y>>z;
v[x].push_back({y,z});
}
for(int i=1; i<=n; i++)
sol[i]=INF;
queue<int> q;
tms[1]=1;
inq[1]=1;
sol[1]=0;
q.push(1);
while(!q.empty())
{
int tp=q.front();
q.pop();
if(tms[tp]>n)
{
outf<<"Ciclu negativ!";
return 0;
}
inq[tp]=false;
for(auto it:v[tp])
{
if(sol[it.first]>sol[tp]+it.second)
{
if(!inq[it.first])
{
q.push(it.first);
tms[it.first]++;
inq[it.first]=true;
}
sol[it.first]=sol[tp]+it.second;
}
}
}
for(int i=2; i<=n; i++)
outf<<sol[i]<<' ';
return 0;
}