CodeForces 【20C】Dijkstra?

时间:2024-09-07 22:04:26

解题思路

heap+Dijkstra就能过。注意边是双向边,要用long long。

附上代码

#include <iostream>
#include <queue>
#include <cstdio>
#include <cstring>
#include <algorithm> using namespace std; typedef pair<long long, int> P;
priority_queue<P, vector<P>, greater<P> > Q;
typedef long long LL;
const int maxnode = 1e5+, maxedge = 2e5+;
int n, m, u[maxedge], v[maxedge], fir[maxnode], nx[maxedge], pre[maxnode], Ans[maxnode];
LL w[maxedge], dis[maxedge], cnt, tot;
inline void addedge(int x, int y, LL z) {
nx[++cnt] = fir[x];
fir[x] = cnt;
u[cnt] = x, v[cnt] = y, w[cnt] = z;
}
inline void Dijkstra() {
fill(dis+, dis++n, );
Q.push(P(, ));
dis[] = ;
int k;
while (!Q.empty()) {
P x = Q.top();
Q.pop();
if(x.first > dis[x.second]) continue;
k = fir[x.second];
while (k != -) {
if(dis[u[k]] + w[k] < dis[v[k]]) {
dis[v[k]] = dis[u[k]] + w[k];
pre[v[k]] = u[k];
Q.push(P(dis[v[k]], v[k]));
}
k = nx[k];
}
}
} int main() {
scanf("%d%d", &n, &m);
memset(fir, -, sizeof(fir));
int x, y; LL z;
for(int i=; i<=m; i++) {
scanf("%d%d%lld", &x, &y, &z);
addedge(x, y, z);
addedge(y, x, z);
}
Dijkstra();
if(dis[n] == ) {
printf("-1\n");
return ;
}
for(int i=n; i>=; i=pre[i]) {
Ans[++tot] = i;
}
for(int i=tot; i>=; i--) printf("%d ", Ans[i]);
}