Pagini recente » Cod sursa (job #4016) | Pandemie | Profil Harry Potter | Profil andrici_cezar | Cod sursa (job #3282893)
#include<bits/stdc++.h>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
const int inf=1e7;
const int nmax=1e5+5;
vector <pair<int,int>> g[nmax];
queue <pair<int,int>> q;
int n, m, d[nmax], fr[nmax];
void bellman (int node)
{
for (int i=1; i<=n; i++)
d[i]=inf;
d[node]=0;
q.push({node,0});
while (!q.empty())
{
int k=q.front().first;
q.pop();
if (fr[k]==n)
{
fout << "Ciclu negativ!";
return;
}
for (auto i:g[k])
{
if (d[i.first]>d[k]+i.second)
{
fr[i.first]++;
d[i.first]=d[k]+i.second;
q.push(i);
}
}
}
}
int main()
{
fin >> n >> m;
for (int i=1; i<=m; i++)
{
int x, y, c;
fin >> x >> y >> c;
g[x].push_back({y,c});
}
bellman(1);
for (int i=2; i<=n; i++)
{
if (d[i]==inf)
fout << 0 << " ";
else
fout << d[i] << " ";
}
}