题解:AT_abc241_f [ABC241F] Skate

题目大意

传送门

大体思路

这是一道比较基础的 bfs 题。

但是本题的 移动 是根据障碍物的位置而变化,所以我们只需要记录第 i i i 行的障碍物的列值,和第 i i i 列的障碍物的行值,用两个 map 数组存储即可,其余跟基本 bfs 没有太大区别,只需要 map 自带的函数 lower_bound 来查询当前方向上离现在的位置最近的障碍物即可。

翻了翻题解,代码都有点长,主要是移动方面写的很乱,我的应该比较好理解吧。

代码如下:

#include <bits/stdc++.h>
using namespace std;
//#define int long long
typedef long long ll;
typedef pair<int, int> pr;
#define up(i, l, r) for(int i = (l); i <= (r); i++)
#define down(i, r, l) for(int i = (r); i >= (l); i--)
const int mod = 1000000007;
const int base = 2333;
const double eps = 1e-6;

inline int read() {
	int x = 0, f = 1; char ch = getchar();
	while(ch < '0' || ch > '9') { if(ch == '-') f = -1; ch = getchar(); }
	while(ch >= '0' && ch <= '9') { x = (x << 1) + (x << 3) + (ch ^ 48); ch = getchar(); }
	return x * f;
}

int h, w, n, sx, sy, fx, fy, ans = 0;
map<pr, int> dis; //范围大,要开 map
map<int, set<int> > row, col; //分别记录每一行的障碍物和每一列的障碍物
queue<pr> q; //bfs 用的队列

inline void add(int x, int y, int dist) {
	if (dis.find(pr(x, y)) == dis.end()) { //判重
		dis[pr(x, y)] = dist;
		q.push(pr(x, y));
	}
}

signed main() {
	h = read(), w = read(), n = read(), sx = read(), sy = read(), fx = read(), fy = read();
	up(i, 1, n) {
		int x = read(), y = read();
		row[x].insert(y), col[y].insert(x);
	}
	q.push(pr(sx, sy));
	dis[pr(sx, sy)] = 0;
	while (!q.empty()) {
		pr u = q.front();
		q.pop();
		int ux = u.first, uy = u.second;
		int dist = dis[pr(ux, uy)];
		if (ux == fx && uy == fy) {
			cout << dist;
			return 0;
		}
		auto it = row[ux].lower_bound(uy); //二分查询
		if (it != row[ux].end()) add(ux, *it - 1, dist + 1); //如果找到了
		if (it != row[ux].begin()) add(ux, *(--it) + 1, dist + 1);
		it = col[uy].lower_bound(ux);
		if (it != col[uy].end()) add(*it - 1, uy, dist + 1);
		if (it != col[uy].begin()) add(*(--it) + 1, uy, dist + 1);
	}
	cout << -1;
	return 0;
}
  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值