Pagini recente » Cod sursa (job #86482) | Cod sursa (job #3170970) | Cod sursa (job #1820072) | Cod sursa (job #3329835) | Cod sursa (job #3310991)
#include <bits/stdc++.h>
#define oo 2000000000
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m, d[50005], cnt[50005];
bool in_coada[50005];
vector< pair<int, int> >L[50005];
queue<int> q;
void Bellman_Ford()
{
int x, nod, cost;
for(int i = 2;i <= n;i++)
d[i] = oo;
q.push(1);
in_coada[1] = 1;
cnt[1] = 1;
while(!q.empty())
{
x = q.front();
q.pop();
in_coada[x] = 0;
for(auto e : L[x])
{
nod = e.first;
cost = e.second;
if(d[nod] > d[x] + cost)
{
d[nod] = d[x] + cost;
if(!in_coada[nod])
{
q.push(nod);
in_coada[nod] = 1;
cnt[nod]++;
if(cnt[nod] > n)
{
fout << "Ciclu negativ!\n";
fout.close();
exit(0);
}
}
}
}
}
}
int main()
{
int i, j, cost;
fin >> n >> m;
while(m)
{
fin >> i >> j >> cost;
L[i].push_back({j, cost});
m--;
}
Bellman_Ford();
for(i = 2;i <= n;i++)
fout << d[i] << " ";
fout << "\n";
fout.close();
return 0;
}