Pagini recente » Cod sursa (job #310837) | Cod sursa (job #2234388) | Cod sursa (job #2261564) | Cod sursa (job #3211307) | Cod sursa (job #3282375)
#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;
for(int i = 1; i <= n; ++i){
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]){
if(i == n){
negative_cycle = true;
return;
}
dist[v] = dist[u] + c;
}
}
}
}
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;
}