Pagini recente » Cod sursa (job #570190) | Cod sursa (job #3239250) | Cod sursa (job #2807186) | Cod sursa (job #308233) | Cod sursa (job #2569571)
#include <fstream>
#include <queue>
#include <vector>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int inf = 1000000000;
int n, m, dist[100005];
int aparitii[100005];
bool inqueue[100005], cycle;
vector<pair<int, int> > g[100005];
void citire() {
fin >> n >> m;
int a, b, c;
while(m--) {
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);
while(!cycle && !q.empty()) {
int curr = q.front();
q.pop();
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();
}