CodeForces - 1073C Vasya and Robot
Vasya has got a robot which is situated on an infinite Cartesian plane, initially in the cell (0,0)
. Robot can perform the following four kinds of operations:
- U — move from (x,y)
to (x,y+1)
- ;
- D — move from (x,y)
- to (x,y−1)
- ;
- L — move from (x,y)
- to (x−1,y)
- ;
- R — move from (x,y)
- to (x+1,y)
Vasya also has got a sequence of n
operations. Vasya wants to modify this sequence so after performing it the robot will end up in (x,y).
Vasya wants to change the sequence so the length of changed subsegment is minimum possible. This length can be calculated as follows: maxID−minID+1
.
If there are no changes, then the length of changed subsegment is 0
. Changing an operation means replacing it with some operation (possibly the same); Vasya can't insert new operations into the sequence or remove them.
Help Vasya! Tell him the minimum length of subsegment that he needs to change so that the robot will go from (0,0)
to (x,y), or tell him that it's impossible.
Input
The first line contains one integer number n (1≤n≤2⋅105)
— the number of operations.
The second line contains the sequence of operations — a string of n
characters. Each character is either U, D, L or R.
The third line contains two integers x,y (−109≤x,y≤109)
— the coordinates of the cell where the robot should end its path.
Output
Print one integer — the minimum possible length of subsegment that can be changed so the resulting sequence of operations moves the robot from (0,0)
to (x,y). If this change is impossible, print −1
.
Examples
Input
5 RURUU -2 3
Output
3
Input
4 RULR 1 1
Output
0
Input
3 UUU 100 100
Output
-1
題解:二分列舉答案,判斷是否存在區間可行- .
#include<iostream>
#include<cstdio>
#include<cmath>
using namespace std;
#define eps 1e-8
const int N=2e5+10;
int n;
char s[N];
int x,y,sx[N],sy[N];
bool judge(int len)
{
for(int i=len;i<=n;i++)
if(fabs(sx[i]-sx[i-len]+x-sx[n])+fabs(sy[i]-sy[i-len]+y-sy[n])<=len&&(int)(len-fabs(sx[i]-sx[i-len]+x-sx[n])+fabs(sy[i]-sy[i-len]+y-sy[n]))%2==0)
return true;
return false;
}
int main()
{
cin>>n>>s+1>>x>>y;
if(fabs(x)+fabs(y)>n||((int)(n-fabs(x)-fabs(y))%2))
{
cout<<"-1"<<endl;
return 0;
}
for(int i=1;i<=n;i++)
{
if(s[i]=='U') sy[i]++;
if(s[i]=='D') sy[i]--;
if(s[i]=='L') sx[i]--;
if(s[i]=='R') sx[i]++;
sx[i]+=sx[i-1];
sy[i]+=sy[i-1];
}
if(sx[n]==x&&sy[n]==y)
{
cout<<0<<endl;
return 0;
}
int l=1,r=n;
// cout<<fabs(sx[4]-sx[4-len]+x-sx[n])+fabs(sy[i]-sy[i-len]+y-sy[n])<<endl;
while(l<r)
{
int mid=(r+l)>>1;
if(judge(mid))
r=mid;
else
l=mid+1;
}
cout<<l<<endl;
return 0;
}