Pagini recente » Cod sursa (job #1451996) | Cod sursa (job #755173) | Cod sursa (job #2514923) | Cod sursa (job #3191654) | Cod sursa (job #1822155)
#include <fstream>
#include <vector>
#include <queue>
using namespace std;
ifstream fin ("bellmanford.in");
ofstream fout ("bellmanford.out");
struct st{
int v, c;
};
const int N = 50010, INF=(1<<30);
int n, m, x, y, z, i, j, v[N], d[N], ok, k, p, u, nr[N];
vector<st> L[N];
st aux;
queue<int> c;
int main(){
fin >> n >> m;
for (i = 2; i <= n; ++i) {
d[i] = INF;
}
for (i = 1; i <= m; ++i) {
fin >> x >> y >> z;
aux.v = y;
aux.c = z;
L[x].push_back(aux);
}
c.push(1);
v[1] = 1;
nr[1] = 1;
while(!c.empty()) {
x = c.front();
c.pop();
v[x] = 0;
for (i = 0; i < L[x].size(); ++i) {
y = L[x][i].v;
if (d[y] > d[x] + L[x][i].c) {
d[y] = d[x] + L[x][i].c;
if (v[y] == 0) {
if (nr[y] == n) {
fout << "Ciclu negativ!\n";
return 0;
}
nr[y]++;
c.push(y);
v[y] = 1;
}
}
}
}
for (i = 2; i <= n; ++i) {
fout << d[i] << ' ';
}
return 0;
}