Pagini recente » Cod sursa (job #1954810) | Cod sursa (job #1919685) | Cod sursa (job #2975927) | Cod sursa (job #502896) | Cod sursa (job #1919822)
#include <iostream>
#include <climits>
#include <fstream>
#include <vector>
using namespace std;
ifstream in("bellmanford.in");
ofstream out("bellmanford.out");
const int NMax = 1e5 + 5;
// bellman-ford clasic
int N,M;
int dist[NMax];
// dist[i] = distanta de la nodul 1 la nodul i
struct muchie {
int y,c;
muchie() {
muchie(1,0);
}
muchie(int a,int b) {
y = a;
c = b;
}
};
vector<muchie> v[NMax];
// v - lista de adiacenta
int main() {
in>>N>>M;
for (int i=1;i<=M;++i) {
int x,y,c;
in>>x>>y>>c;
muchie e(y,c);
v[x].push_back(e);
}
for (int i=2;i<=N;++i) {
dist[i] = 1e8;
}
dist[1] = 0;
bool update = true;
for (int ct=1;ct<=N;++ct) {
if (!update) {
break;
}
update = false;
for (int i=1;i<=N;++i) {
vector<muchie>::iterator it;
for (it=v[i].begin();it<v[i].end();++it) {
if (dist[(it->y)] > dist[i] + (it->c)) {
dist[(it->y)] = dist[i] + (it->c);
update = true;
}
}
}
}
if (update) {
out<<"Ciclu negativ!";
}
else {
for (int i=2;i<=N;++i) {
out<<dist[i]<<' ';
}
return 0;
}
in.close();out.close();
return 0;
}