Pagini recente » Cod sursa (job #2943136) | Cod sursa (job #1932622) | Cod sursa (job #1362403) | Cod sursa (job #2770473) | Cod sursa (job #2374571)
#include <iostream>
#include <fstream>
#include <algorithm>
#include <vector>
#include <utility>
#include <cmath>
#include <string>
#include <cstring>
#include <set>
#include <queue>
#include <map>
#include <stack>
#include <iomanip>
#define ll long long
#define lsb(x) (x & -x)
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int INF = 1e9;
int main() {
int n, m;
in >> n >> m;
vector<vector<pair<int, int>>> g(n + 1);
for(int i = 1; i <= m; i ++) {
int x, y, c;
in >> x >> y >> c;
g[x].push_back({y, c});
}
queue<int> q;
vector<int> dist(n + 1, INF);
vector<bool> inq(n + 1, 0);
vector<int> cnt(n + 1, 0);
dist[1] = 0;
q.push(1);
inq[1] = 1;
while(q.size()) {
auto node = q.front();
q.pop();;
inq[node] = 0;
for(auto it : g[node]) {
if(dist[it.first] > dist[node] + it.second) {
dist[it.first] = dist[node] + it.second;
if(!inq[it.first]) {
inq[it.first] = 1;
q.push(it.first);
cnt[it.first] ++;
if(cnt[it.first] > n) {
out << "Ciclu negativ!";
return 0;
}
}
}
}
}
for(int i = 2; i <= n; i ++)
out << dist[i] << " ";
return 0;
}