Pagini recente » Cod sursa (job #80611) | Cod sursa (job #1338904) | Cod sursa (job #2640349) | Cod sursa (job #810254) | Cod sursa (job #3271662)
#include <iostream>
#include <fstream>
#include <utility>
#include <vector>
#include <stdlib.h>
#include <cstring>
#include <set>
#include <queue>
#define nmax 50000
#define Inf 10000000
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
int n, m;
vector<pair<int, int>> Graf[nmax + 1];
int dist[nmax], viz[nmax];
vector<int> Nciclu;
void bellmanford(int varf)
{
for (int i = 1; i <= n; i++)
dist[i] = Inf;
dist[varf] = 0;
queue<pair<int, int>> q;
q.push({0, varf});
viz[varf] = 1;
bool ok = 1;
while (!q.empty() && ok == 1)
{
int nod = q.front().second;
q.pop();
viz[nod]++;
if (viz[nod] == n)
{
ok = 0;
break;
}
else
{
for (auto neigh : Graf[nod])
{
if (dist[neigh.first] > dist[nod] + neigh.second)
{
dist[neigh.first] = dist[nod] + neigh.second;
q.push({dist[neigh.first], neigh.first});
}
}
}
}
if (ok == 0)
{
fout << "Ciclu negativ!";
}
else
{
for (int i = 2; i <= n; i++)
{
fout << dist[i] << " ";
}
}
}
int main()
{
fin >> n >> m;
for (int i = 1; i <= m; i++)
{
int x, y, c;
fin >> x >> y >> c;
Graf[x].push_back({y, c});
}
bellmanford(1);
return 0;
}