Pagini recente » Cod sursa (job #2018014) | Cod sursa (job #1161714) | Cod sursa (job #1703543) | Cod sursa (job #2645949) | Cod sursa (job #1921925)
#include <iostream>
#include <fstream>
#include <vector>
#include <queue>
#define DM 50005
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m, a, b, c, viz[DM], dist[DM];
const int INF = (1 << 30);
vector <pair<int, int> > g[DM];
queue <int> q;
void bellman_ford()
{
for(int i = 2; i <= n; i++)
dist[i] = INF;
q.push(1);
while(!q.empty())
{
int nod = q.front();
q.pop();
for(auto it : g[nod])
if(dist[it.first] > dist[nod] + it.second)
{
dist[it.first] = dist[nod] + it.second;
q.push(it.first);
viz[it.first]++;
if(viz[it.first] > n)
{
fout << "Ciclu negativ!";
return;
}
}
}
for(int i = 2; i <= n; i++)
fout << dist[i] << ' ';
}
int main()
{
fin >> n >> m;
for(int i = 1; i <= m; i++)
{
fin >> a >> b >> c;
g[a].push_back(make_pair(b,c));
}
bellman_ford();
return 0;
}