给定一行操作指令(字符串)s:上下左右,机器人会按指令移动,q次询问:x, y, l, r, 即先将s的[l, r]子串reverse,再按指令移动,是否经过(x,y)

本文介绍了如何使用C++实现一个二维空间中的路径搜索算法,通过`Point`结构、操作符重载以及`map`数据结构,解决给定起点和终点在经过一系列方向变化后到达目标位置的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目

#include<bits/stdc++.h>
using namespace std;
const int maxn = 2e5 + 5;

struct Point{
	int x, y;
	bool operator < (const Point &u) const{
		if(x != u.x) return x < u.x;
		return y < u.y;
	}
	Point operator + (Point u){
		return Point{x + u.x, y + u.y};
	}
};
Point point[maxn];//按原指令移动会经过哪些点
//vector<int> vec[maxn];
map<Point, vector<int>> mp;//mp[{x, y}]存走到(x, y)需要移动几步
Point change(char ch){
	if(ch == 'U') return {0, 1};
	else if(ch == 'D') return {0, -1};
	else if(ch == 'L') return {-1, 0};
	else return {1, 0};
}
bool search(Point goal, int x, int y, int l, int r){
	l--;//l--后,reverse对point[l, r]这些点没影响,
	    //reverse后,point[l + 1, r - 1]这些点会变成关于point[l]和point[r]连线的中点 中心对称的点
	auto it = lower_bound(mp[goal].begin(), mp[goal].end(), r);
	if(it != mp[goal].end()) return 1;
	it = upper_bound(mp[goal].begin(), mp[goal].end(), l);
	if(mp[goal].size() && it != mp[goal].begin()) return 1;
	int x1 = point[l].x, y1 = point[l].y;
	int x2 = point[r].x, y2 = point[r].y;
	goal = {x1 + x2 - x, y1 + y2 - y};
	it = upper_bound(mp[goal].begin(), mp[goal].end(), l);
	if(it == mp[goal].end()) return 0;
	return (*it) < r;
}
void solve(){
	int n, i, j, q;
	cin >> n >> q;
	// for(i = 1; i <= n; i++){
	// 	cin >> a[i];
	// }
	string s;
	cin >> s;
	s = " " + s;
	Point cur = {0, 0};
	int m = 0;
	point[0] = cur;
	mp[cur].push_back(0);
	for(i = 1; i <= n; i++){
		Point d = change(s[i]);
		cur = cur + d;
		point[++m] = cur;
		mp[{cur}].push_back(i);
	}
	while(q--){
		int x, y, l, r;
		cin >> x >> y >> l >> r;
		Point goal = {x, y};
		int flag = search(goal, x, y, l, r);
		if(flag) cout << "YES\n";
		else cout << "NO\n";
	}
}
int main(){
	ios::sync_with_stdio(0);
	cin.tie(0);
	int T = 1;
	//cin >> T;
	while(T--){
		solve();
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

__night_

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值