Pagini recente » Cod sursa (job #1246444) | Cod sursa (job #916949) | Cod sursa (job #1888355) | Cod sursa (job #1693363) | Cod sursa (job #1400843)
#include <fstream>
#include <vector>
#include <queue>
#include <climits>
#define INF INT_MAX
#define NMAX 50001
using namespace std;
struct arc {int y, c;};
bool viz[NMAX];
int nr[NMAX];
vector<arc> v[9];
int main() {
int n, d[NMAX], m, x, negativ = 0, i;
arc z;
queue<int> l;
ifstream in("bellmanford.in");
in >> n >> m;
for (i = 1; i <= m; i++) {
in >> x >> z.y >> z.c;
v[x].push_back(z);
}
in.close();
/*for (i = 1; i <= n; i++)
for (vector<arc>::iterator it = v[i].begin(); it != v[i].end(); it++)
out << i << ' ' << it->y << ' ' << it->c << ' ';*/
for (i = 1; i <= n; i++)
d[i] = INF;
d[1] = 0;
l.push(1);
viz[1] = 1;
while (!l.empty() && !negativ) {
for (vector<arc>::iterator it = v[l.front()].begin(); it != v[l.front()].end(); it++)
if (d[it->y] > d[l.front()] + d[it->c]) {
d[it->y] = d[l.front()] + d[it->c];
if (!viz[it->y]) {
if (nr[it->y] == n)
negativ = 1;
l.push(it->y);
viz[it->y] = 1;
nr[it->y]++;
}
}
viz[l.front()] = 0;
l.pop();
}
ofstream out("bellmanford.out");
if (negativ)
out << "Ciclu negativ!";
else for (i = 2; i <= n; i++)
out << d[i] << ' ';
out.close();
return 0;
}