Pagini recente » Cod sursa (job #760813) | Cod sursa (job #944244) | Cod sursa (job #2887795) | Cod sursa (job #2802376) | Cod sursa (job #3194858)
#include <bits/stdc++.h>
using namespace std;
const int oo = 1e9;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
int ciclu_neg;
int d[50005];
int cnt[50005];
int viz[50005];
vector<pair<int, int>> V[50005];
queue<pair<int, int>> q;
void Citire()
{
fin >> n >> m;
for(int i = 1; i <= m;i++)
{
int x, y, c;
fin >> x >> y >> c;
V[x].push_back({y, c});
}
}
void Bellman_Ford()
{
for(int i = 2;i <= n;i++)
d[i] = oo;
q.push({1, 0});
while(!q.empty())
{
int nod = q.front().first;
q.pop();
viz[nod] = 0;
if(cnt[nod] == n)
{
fout << "Ciclu negativ!";
exit(0);
}
for(auto x : V[nod])
if(d[x.first] > d[nod] + x.second)
{
d[x.first] = d[nod] + x.second;
cnt[x.first]++;
if(viz[x.first] == 0)
{
viz[x.first] = 1;
q.push({x.first, d[x.first]});
}
}
}
for(int i= 2;i <= n;i++)
fout << d[i] << " ";
}
int main()
{
Citire();
Bellman_Ford();
return 0;
}