Pagini recente » Cod sursa (job #859643) | Cod sursa (job #2109819) | Cod sursa (job #2301314) | Cod sursa (job #1862271) | Cod sursa (job #3282379)
#include <fstream>
#include <vector>
using namespace std;
ifstream fin("bellmanford.in");
ofstream fout("bellmanford.out");
const int NMAX = 50001;
const int INF = 1e9;
struct Muchie{
int from, to, cost;
};
vector <Muchie> g;
int dist[NMAX];
int n, m;
bool negative_cycle;
void BellmanFord(){
for(int i = 1; i <= n; ++i){
dist[i] = INF;
}
dist[1] = 0;
bool updated;
for(int i = 1; i < n; ++i){
updated = false;
for(auto edge:g){
int u = edge.from;
int v = edge.to;
int c = edge.cost;
if(dist[u] != INF && dist[u] + c < dist[v]){
dist[v] = dist[u] + c;
updated = true;
}
}
if(updated == false){
break;
}
}
for (auto edge:g) {
int u = edge.from, v = edge.to, c = edge.cost;
if (dist[u] != INF && dist[u] + c < dist[v]) {
negative_cycle = true;
return;
}
}
}
void solve(){
fin >> n >> m;
for(int i = 1; i <= m; ++i){
int x, y, c;
fin >> x >> y >> c;
Muchie temp;
temp.from = x;
temp.to = y;
temp.cost = c;
g.push_back(temp);
}
BellmanFord();
if(negative_cycle == true){
fout << "Ciclu negativ!";
}
else{
for(int i = 2; i <= n; ++i){
fout << dist[i] << " ";
}
}
}
int main()
{
solve();
return 0;
}