4217. 机器人移动
思路:
比较细节的是判定
−
1
-1
−1,步数不够很好想,但是还要满足步数奇偶性的判定
(
a
b
s
(
a
)
+
a
b
s
(
b
)
)
%
2
!
=
n
%
2
(abs(a) + abs(b)) \ \% \ 2 \ != n\ \% \ 2
(abs(a)+abs(b)) % 2 !=n % 2
c
h
e
c
k
check
check 函数,如果修改这一段,只要删除这一段后位置与终点位置二维曼哈顿距离小于等于步数就可以到达
code:
#include<bits/stdc++.h>
#define endl '\n'
#define ll long long
#define ull unsigned long long
#define ld long double
#define all(x) x.begin(), x.end()
#define eps 1e-6
using namespace std;
const int maxn = 2e6 + 9;
const int mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const ll INF = 0x3f3f3f3f3f3f3f3f;
ll n, m;
int f(char x){
if(x == 'U') return 0;
else if(x == 'D') return 1;
else if(x == 'L') return 2;
else return 3;
}
int sum[maxn][4];
int dfx, dfy;
int a, b;
bool check(int x){
//cout << "x = " << x << endl;
for(int i = x; i <= n; ++i){
int dx = dfx, dy = dfy;
dx -= sum[i][0] - sum[i-x][0];// U
dx += sum[i][1] - sum[i-x][1];// D
dy += sum[i][2] - sum[i-x][2];// L
dy -= sum[i][3] - sum[i-x][3];// R
// cout << i << " " << dx << " " << dy << endl;
if(abs(dx-a) + abs(dy-b) <= x) return 1;
}
return 0;
}
void work()
{
cin >> n;
string s;cin >> s;s = "@" + s;
cin >> b >> a;
if(abs(a) + abs(b) > n || (abs(a) + abs(b)) % 2 != n % 2) cout << -1 << endl;
else
{
for(int i = 1; i <= n; ++i){
for(int j = 0; j < 4; ++j)
sum[i][j] = sum[i-1][j];
sum[i][f(s[i])]++;
}
/* for(int i = 1; i <= n; ++i)
for(int j = 0; j < 4; ++j)
cout << sum[i][j] << " \n"[j==3];*/
for(int i = 1; i <= n; ++i){
if(s[i] == 'U') ++dfx;
else if(s[i] == 'D') --dfx;
else if(s[i] == 'L') --dfy;
else ++dfy;
}
// cout << dfx << " " << dfy << endl;
int l = 0, r = n;
while(l < r)
{
int mid = (l + r) >> 1;
if(check(mid)) r = mid;
else l = mid + 1;
}
// cout << check(l) << endl;
cout << l << endl;
}
}
int main()
{
ios::sync_with_stdio(0);
// int TT;cin>>TT;while(TT--)
work();
return 0;
}