Pagini recente » Cod sursa (job #1756656) | Istoria paginii utilizator/monalisa001 | Istoria paginii utilizator/llamacorn | Profil M@2Te4i | Cod sursa (job #2574792)
#include <fstream>
#include <queue>
#include <vector>
#include <iostream>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int inf = 1000000000;
vector<pair<int, int> > g[50005];
int n, m;
int dist[50005];
bool inqueue[50005], cycle;
int aparitii[50005];
void citire() {
fin >> n >> m;
while(m--) {
int a, b ,c;
fin >> a >> b >> c;
g[a].push_back({b, c});
}
}
void solve() {
for(int i = 1; i <= n; i++) dist[i] = inf;
dist[1] = 0;
queue<int> q;
q.push(1);
inqueue[1] = 1;
while(!q.empty() && !cycle) {
int curr = q.front();
q.pop();
inqueue[curr] = 0;
aparitii[curr]++;
if(aparitii[curr] > n) {
cycle = true;
continue;
}
for(auto next: g[curr])
if(dist[curr]+next.second < dist[next.first]) {
dist[next.first] = dist[curr]+next.second;
if(!inqueue[next.first]) q.push(next.first);
}
}
if(cycle)
fout << "Ciclu negativ!";
else
for(int i = 2; i <= n; i++)
fout << dist[i] << ' ';
}
int main() {
citire();
solve();
}