Pagini recente » Cod sursa (job #555923) | Cod sursa (job #55510) | Cod sursa (job #1357701) | Cod sursa (job #1214793) | Cod sursa (job #3235644)
#include <vector>
#include <algorithm>
#include <queue>
#include <fstream>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int N = 5e4;
const int M = 3e5;
const int INF = 6e7;
struct arc{
int varf, cost;
};
int d[N + 1], n, m, nrinq[N + 1];
bool inq[N + 1];
vector<arc> a[N + 1];
queue<int> q;
bool neg(){
d[1] = 0;
q.push(1);
inq[1] = 1;
nrinq[1] = 1;
for(int i = 2; i <= n; i++){
d[i] = INF;
inq[i] = 0;
nrinq[i] = 0;
}
while(!q.empty()){
int x = q.front();
q.pop();
inq[x] = 0;
for(auto p : a[x]){
int y = p.varf, c = p.cost;
if(d[x] + c < d[y]){
d[y] = d[x] + c;
if(!inq[y]){
q.push(y);
inq[y] = 1;
nrinq[y]++;
if(nrinq[y] == n){
return true;
}
}
}
}
}
return false;
}
int main() {
in >> n >> m;
for(int i = 0; i < m; i++){
int x, y, c;
in >> x >> y >> c;
a[x].push_back((arc){y, c});
}
if(neg()){
out << "Ciclu negativ!\n";
}
else{
for(int i = 2; i <= n; i++){
out << d[i] << " ";
}
}
return 0;
}