题解:P1491 集合位置
分享一篇使用 bitset 存路径的题解,思路清新代码短。
显然我们可以使用 dijkstra 跑最短路,同时维护一个次短路。每次更新时优先更新最短路,如果更新不了就尝试次短路。
因为精度不要求,所以不需要特殊处理。
一开始把最小值和次小值都设置为无穷大(
几点要注意的:
- 读入要建双向边。
- 每次更新 bitset 的值后要更新回来,否则会带入下一次更新。
代码如下,十分简洁易懂,比删边的算法好想的多:
#include <bits/stdc++.h>
using namespace std;
const int N = 11000;
int n, m;
double fir[N], sec[N];
int x[210], y[210];
vector<pair<int, double> > e[N];
double getdis(int xl, int xr, int yl, int yr) {
return sqrt((xr - yr) * (xr - yr) + (xl - yl) * (xl - yl));
}
struct node {
int u;
double dis;
bitset<210> bt;
bool operator < (const node& cmp) const {
return dis > cmp.dis;
}
};
priority_queue<node> q;
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d%d", &x[i], &y[i]);
fir[i] = sec[i] = 1e9;
}
for (int i = 1; i <= m; i++) {
int u, v;
scanf("%d%d", &u, &v);
e[u].push_back(make_pair(v, getdis(x[u], y[u], x[v], y[v])));
e[v].push_back(make_pair(u, getdis(x[u], y[u], x[v], y[v])));
}
bitset<210> epty;
epty[1] = 1;
q.push(node{1, 0, epty});
fir[1] = 0;
while (!q.empty()) {
node f = q.top();
q.pop();
if (f.dis > sec[f.u]) {
continue;
}
for (auto v : e[f.u]) {
int to = v.first;
if (f.bt[to] == 1) continue;
f.bt[to] = 1;
double cst = v.second;
if (fir[to] > f.dis + cst) {
sec[to] = fir[to];
fir[to] = f.dis + cst;
q.push(node{to, f.dis + cst, f.bt});
} else if (sec[to] > f.dis + cst) {
sec[to] = f.dis + cst;
q.push(node{to, f.dis + cst, f.bt});
}
f.bt[to] = 0;
}
}
if (sec[n] != 1e9) printf("%.2lf", sec[n]);
else printf("-1");
return 0;
}