跳到正文

题解

题解:P1491 集合位置

Pratty约 3 分钟
原文
文章信息与版本

文章信息

发布
2025年11月4日
收录
2026年4月15日
更新
2026年11月11日
篇幅
约 3 分钟
题目
P1491

版本

  1. v1当前

分享一篇使用 bitset 存路径的题解,思路清新代码短。

显然我们可以使用 dijkstra 跑最短路,同时维护一个次短路。每次更新时优先更新最短路,如果更新不了就尝试次短路。

因为精度不要求,所以不需要特殊处理。

一开始把最小值和次小值都设置为无穷大(10910^9),但是节点 11 的最小值要设置为 00。

几点要注意的:

  • 读入要建双向边。
  • 每次更新 bitset 的值后要更新回来,否则会带入下一次更新。

代码如下,十分简洁易懂,比删边的算法好想的多:

C++
#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;
}
原文
存档评论1 条抓取于