Educational Codeforces Round 53 (Rated for Div. 2) C. Vasya and Robot(二分+模拟)

版权声明:若转载请附上原博客链接,谢谢! https://blog.csdn.net/Link_Ray/article/details/83509959

题目链接

题意

一个二维平面上有个机器人初始在 ( 0 , 0 ) (0,0) ,它可以上下左右移动,现在给出一串长度 n n 且只包含 L , R , U , D L(左),R(右),U(上),D(下) 的命令串,我们可以任意修改其中任何一个命令,使其可以到达终点 ( x , y ) (x,y) 。但需要修改的命令的最左位置和最右位置距离最小。例如 L R L U U LRLUU 修改为 U R U R R URURR 修改的位置为1,3,4,5,其距离为 ( 5 1 ) + 1 = 5 (5-1)+1=5

题解

L e n = a b s ( x + y ) Len = abs(x+y) ,如果 n < l e n n < len 或者 n n l e n len 的奇偶性不同,那肯定不能走到终点。
其余情况肯定有办法走到终点。
这里二分答案。 现在假设可以修改长度为x的区间。那其实相当于已经走了这个区间以外的命令而到达了 ( x 0 , y 0 ) (x_0,y_0) ,因为这个区间我们可以随意修改命令,相当于从 ( x 0 , y 0 ) (x_0,y_0) 到终点 ( x , y ) (x,y) 通过x步能不能走到。这就转换成了刚刚讨论过的问题了。可以通过滑动窗口的方法判断在长度为x下的不同的 ( x 0 , y 0 ) (x_0,y_0)

代码

#include <bits/stdc++.h>
using namespace std;
#define x first
#define y second
typedef pair<int,int> pii;

const int maxn = 2e5+5;

char s[maxn];
int n,x,y;
// 好妙的行走函数
void walk(pii& p, char opt, int d) {
	if(opt == 'L') 
		p.x -= d;
	else if(opt == 'R')
		p.x += d;
	else if(opt == 'U')
		p.y += d;
	else if(opt == 'D')
		p.y -= d;
}
bool can(pii p1, pii p2, int len) {
	int dis = abs(p1.x-p2.x)+abs(p1.y-p2.y);
	if(dis < len || dis%2 != len%2) return false;
	return true;
}
bool ok(int x) {
	int l = 1, r = l+x-1;
	pii pos = make_pair(0,0);
	for(int i = r+1; i <= n; ++i) {
		walk(pos, s[i], 1);
	}
	pii end = make_pair(x,y);

	while(r <= n) {
		if(!can(pos, end, x)) {
			walk(pos, s[l++], 1);
			walk(pos, s[++r], -1);
		}
		else 
			return true;
	}
	return false;
}
int main() {
	scanf("%d", &n);
	scanf("%s", s+1);
	scanf("%d%d", &x, &y);

	if(!can(pii(0,0), pii(x,y), n)) {
		puts("-1");
		exit(0);
	}

	int l = 1, r = n, ans = -1;
	while(l <= r) {
		int mid = (l+r) >> 1;
		if(ok(mid)) {
			ans = mid;
			r = mid-1;
		}
		else 
			l = mid+1;
	}
	printf("%d\n", ans);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/Link_Ray/article/details/83509959