Pagini recente » Cod sursa (job #3235249) | Cod sursa (job #1873917) | Cod sursa (job #1739267) | Cod sursa (job #2486047) | Cod sursa (job #1929435)
#include <stdio.h>
#include <ctype.h>
#include <limits.h>
#include <vector>
#include <queue>
using namespace std;
FILE *fin = fopen("bellmanford.in", "r"), *fout = fopen("bellmanford.out", "w");
#define BUF 1 << 17
int pos = BUF;
char buf[BUF];
inline char next() {
if(pos == BUF)
fread(buf, 1, BUF, fin), pos = 0;
return buf[pos++];
}
inline int read() {
int x = 0, semn = 1;
char ch = next();
while(!isdigit(ch) && ch != '-')
ch = next();
if(ch == '-')
semn = -1, ch = next();
while(isdigit(ch))
x = x * 10 + ch - '0', ch = next();
return x * semn;
}
struct atom {
int nod;
int cost;
};
#define NMAX 50000
vector <atom> v[NMAX + 1];
int d[NMAX + 1];/* costurile */
int w[NMAX + 1];/* de cate ori a aparut nodul */
int N, M;
inline void bellman(int nod) {
queue <int> q;
q.push(nod);
d[nod] = 0;
while(!q.empty()) {
int el = q.front();
w[el]++;
if(w[el] > N) {
fputs("Ciclu negativ!\n", fout);
return;
}
for(unsigned int i = 0;i < v[el].size();i++) {
int uau = v[el][i].nod;
int cost = v[el][i].cost;
if(d[el] + cost < d[uau]) {
d[uau] = d[el] + cost;
q.push(uau);
}
}
q.pop();
}
for(int i = 2;i <= N;i++)
fprintf(fout, "%d ", d[i]);
fputc('\n', fout);
}
int main() {
N = read(), M = read();
for(int i = 1;i <= M;i++) {
int x, y, c;
x = read(), y = read(), c = read();
v[x].push_back({y, c});
}
for(int i = 1;i <= N;i++)
d[i] = INT_MAX;
bellman(1);
fclose(fin);
fclose(fout);
return 0;
}