Codeforces C. Vasya and Robot+二分

U — (x,y)->(x,y+1)
D — (x,y)->(x,y−1)
L — (x,y)->(x−1,y)
R — (x,y)->(x+1,y)

L U L UU 所有改变的长度为3

``````#include<bits/stdc++.h>
#define maxn 1000010
using namespace std;

struct A
{
int x;
int y;
};

A a[200005]={{0}}, b[200005]={{0}};
char ch[200005];
int n, x, y;

int ef(int k)
{
for(int i=0;i<=n-k;i++)
{
A t;
t.x=a[i].x+b[i+k+1].x;
t.y=a[i].y+b[i+k+1].y;
int len=abs(x-t.x)+abs(y-t.y);
if(len<=k&&len%2==k%2)/*判断是否满足解*/
{
return 1;
}
}
return -1;
}

int main()
{
scanf("%d",&n);
scanf("%s",ch+1);
scanf("%d%d",&x,&y);

if(abs(x)+abs(y)>n)
{
printf("-1\n");
return 0;
}

a[0]={0};
for(int i=1;i<=n;i++)/*从前到后扫描**/
{
a[i]=a[i-1];
if(ch[i]=='U')
a[i].y=a[i].y+1;
else if(ch[i]=='D')
a[i].y=a[i].y-1;
else if(ch[i]=='L')
a[i].x=a[i].x-1;
else if(ch[i]=='R')
a[i].x=a[i].x+1;
}

b[n+1]={0};
for(int i=n;i>=1;i--)/*从后到前扫描*/
{
b[i]=b[i+1];
if(ch[i]=='U')
b[i].y=b[i+1].y+1;
else if(ch[i]=='D')
b[i].y=b[i+1].y-1;
else if(ch[i]=='L')
b[i].x=b[i+1].x-1;
else if(ch[i]=='R')
b[i].x=b[i+1].x+1;
}

int l=0, r=n, k=-1;
while(l<=r)/*二分*/
{
int mod=(l+r)/2;
if(ef(mod)<0)
l=mod+1;
else
r=mod-1, k=mod;
}
printf("%d\n",k);

return 0;
}
``````