Pagini recente » Cod sursa (job #2858440) | Cod sursa (job #2858443) | Cod sursa (job #3336428) | Cod sursa (job #3336377) | Cod sursa (job #3336811)
#include <bitset>
#include <filesystem>
#include <fstream>
#include <queue>
#include <random>
#include <vector>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
vector<vector<pair<int, int> > > muchii(50005);
int contor[50005];
bitset<50005> viz;
int cost[50005];
queue<int> coada;
int n, m;
int exista_ciclu;
void bellmanford(int nod) {
viz[nod] = 1;
contor[nod]++;
cost[nod] = 0;
coada.push(nod);
while (coada.size() != 0) {
int nod_curent = coada.front();
coada.pop();
viz[nod_curent] = 0;
if (contor[nod_curent]>n-1) {
exista_ciclu = 1;
}
for (auto vecin: muchii[nod_curent]) {
int nod_vecin = vecin.first;
int cost_vecin = vecin.second;
if (cost[nod_vecin] > cost[nod_curent] + cost_vecin) {
cost[nod_vecin] = cost[nod_curent] + cost_vecin;
if (viz[nod_vecin] == 0) {
coada.push(nod_vecin);
viz[nod_vecin] = 1;
}
contor[nod_vecin]++;
if (contor[nod_vecin]>n-1) {
exista_ciclu = 1;
break;
}
}
}
}
}
int main() {
fin >> n >> m;
for (int i = 1; i <= m; i++) {
int a, b, c;
fin >> a >> b >> c;
muchii[a].push_back({b, c});
}
for (int i = 1; i <= n; i++) {
cost[i] = 10000000;
}
bellmanford(1);
if (exista_ciclu == 0) {
for (int i = 2 ;i<=n ;i++) {
fout<<cost[i]<<" ";
}
}else {
fout<<"Ciclu negativ!";
}
}