Pagini recente » Cod sursa (job #507068) | Cod sursa (job #1238382) | Cod sursa (job #1161958) | Cod sursa (job #1187518) | Cod sursa (job #1435031)
#include <stdio.h>
#include <queue>
#define MAX_N 50001
#define INF 0x7fffffff
using namespace std;
int n, m;
struct lant {
int nod_;
int cost_;
lant(int nod, int cost) : nod_(nod), cost_(cost) { }
};
vector<lant> graf[MAX_N];
bool viz[MAX_N];
int cost[MAX_N];
void solve();
int main() {
freopen("dijkstra.in", "r", stdin);
freopen("dijkstra.out", "w", stdout);
scanf("%d %d", &n, &m);
int i;
int x, y, c;
for (i = 2; i <= n; i++) {
cost[i] = INF;
}
for (i = 1; i <= m; i++) {
scanf("%d %d %d", &x, &y, &c);
graf[x].push_back(lant(y, c));
}
solve();
for (i = 2; i <= n; i++) {
if (cost[i] == INF)
cost[i] = 0;
printf("%d ", cost[i]);
}
printf("\n");
return 0;
}
class comparator {
public:
bool operator() (const int &lh, const int &rh) const {
return cost[lh] > cost[rh];
}
};
#ifdef XIO_DEBUG
#define log(x...) (printf(x),printf("\n"))
#else
#define log(x...) ;
#endif
void solve() {
priority_queue<int, vector<int>, comparator> coada;
vector<lant>::const_iterator i;
log("dijkstra");
coada.push(1);
while (!coada.empty()) {
int top = coada.top();
coada.pop();
log("pop nod: %d cost: %d", top, cost[top]);
viz[top] = true;
for (i = graf[top].begin(); i != graf[top].end(); ++i) {
if (viz[i->nod_])
continue;
bool conditie = cost[top] + i->cost_ < cost[i->nod_];
log(" %d + %d < %d (nod: %d) = %s", cost[top], i->cost_, cost[i->nod_], i->nod_, conditie?"da":"nu");
if (conditie) {
cost[i->nod_] = cost[top] + i->cost_;
coada.push(i->nod_);
}
}
}
}