Pagini recente » Cod sursa (job #877309) | Cod sursa (job #703811) | Cod sursa (job #2654430) | Cod sursa (job #425654) | Cod sursa (job #1779450)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
#define MAX 50010
#define inf 1e9
vector <pair<int, int> > G[MAX];
queue <int> Q;
int dist[MAX], ap[MAX];
int main()
{
int n, m, x, y, c, i, cm, nod;
fin >> n >> m;
cm = m;
while(m--)
{
fin >> x >> y >> c;
G[x].push_back(make_pair(y, c));
}
dist[1] = 0;
for(i = 2 ; i <= n ; i++)
{
dist[i] = inf;
}
Q.push(1);
while(Q.size())
{
nod = Q.front();
Q.pop();
ap[nod]++;
if(ap[nod] > cm)
{
fout << "Ciclu negativ!\n";
return 0;
}
for(auto it : G[nod])
{
if(dist[nod] + it.second < dist[it.first])
{
dist[it.first] = dist[nod] + it.second;
Q.push(it.first);
}
}
}
for(i = 2 ; i <= n ; i++)
{
cout << dist[i] << ' ';
}
cout << "\n";
}