Pagini recente » Cod sursa (job #1149141) | Cod sursa (job #1533370) | Cod sursa (job #1565093) | Cod sursa (job #1817555) | Cod sursa (job #2566825)
#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() {
queue<int> q;
for(int i = 1; i <= n; i++)
dist[i] = inf;
dist[1] = 0;
q.push(1);
while(!q.empty() && !cycle) {
int curr = q.front();
q.pop();
inqueue[curr] = false;
for(int i = 0; i < g[curr].size(); i++) {
int next = g[curr][i].first;
if(dist[next] > dist[curr]+g[curr][i].second) {
dist[next] = dist[curr]+g[curr][i].second;
if(!inqueue[next]) {
q.push(next);
aparitii[next]++;
inqueue[next] = true;
if(aparitii[next] > n)
cycle = true;
}
}
}
}
if(cycle) fout << "Ciclu negativ!";
else for(int i = 2; i <= n; i++)
fout << dist[i] << ' ';
}
int main() {
citire();
solve();
}