Pagini recente » Cod sursa (job #2902776) | Cod sursa (job #2830089) | Cod sursa (job #2359643) | Cod sursa (job #3151618) | Cod sursa (job #2966057)
#include <fstream>
#include <algorithm>
#include <cmath>
#include <cstring>
#include <vector>
#include <queue>
#define ll long long
#define pb push_back
#define bg begin()
#define ed end()
#define cl clear()
#define pi pair<int, int>
///#define int ll
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int MOD = 1e9;
const char nl = '\n';
const int NMAX = 50000;
const int INF = 1e9;
struct graph{
int node, weight;
};
int dist[NMAX + 5], f[NMAX + 5], n, m;
vector <graph> v[NMAX + 5];
queue <int> q;
bool inqueue[NMAX + 5], cycle = false;
void blf(int source){
for(int i = 1; i <= n; ++i)
dist[i] = INF;
q.push(source);
dist[source] = 0, f[source] = 1, inqueue[source] = 1;
while(!q.empty()){
int cur = q.front();
if(f[cur] == n - 1){
cycle = true;
return;
}
for(auto it: v[cur]){
if(dist[cur] + it.weight < dist[it.node]){
dist[it.node] = dist[cur] + it.weight;
if(inqueue[it.node] == 0){
q.push(it.node);
f[it.node]++;
}
}
}
inqueue[cur] = 0;
q.pop();
}
}
void solve(){
blf(1);
if(cycle == true)
out << "Ciclu negativ!";
else{
for(int i = 2; i <= n; ++i)
out << dist[i] << ' ';
out << nl;
}
}
int main(){
in >> n >> m;
for(int i = 1; i <= m; ++i){
int a, b, w;
in >> a >> b >> w;
v[a].push_back({b, w});
}
solve();
return 0;
}