Vasya and Robot (CodeForces - 1073C)
cf上一道题,不知道前缀和怎么也找不到做法。
其实是二分检查时用到前缀和,代码如下:
#include <cstring>
#include <iostream>
#include <cstdio>
#include <queue>
#include <vector>
#include <algorithm>
#include <cmath>
using namespace std;
typedef long long ll;
const int maxn=2*1e5+10;
int n,x,y;
char op[maxn];
int px[maxn],py[maxn];
int check(int f1,int f2)
{
int nowy=py[f1-1]+py[n]-py[f2];
int nowx=px[f1-1]+px[n]-px[f2];
int length=f2-f1+1;
if(length<abs(x-nowx)+abs(y-nowy))
return 1;
if(length%2+(abs(x-nowx)+abs(y-nowy))%2==1)
return 1;
return 0;
}
bool ok(int l)
{
int ans=1;
for(int i=1;i<=n-l+1;i++)
ans*=check(i,i+l-1);
if(ans==1)
return false;
else
return true;
}
int main() {
scanf("%d",&n);
scanf("%s",op+1);
scanf("%d%d",&x,&y);
memset(px,0,sizeof(px));
memset(py,0,sizeof(py));
for(int i=1;i<=n;i++)
{
if(op[i]=='R')
{
px[i]=px[i-1]+1;
py[i]=py[i-1];
}
else if(op[i]=='L')
{
px[i]=px[i-1]-1;
py[i]=py[i-1];
}
else if(op[i]=='U')
{
px[i]=px[i-1];
py[i]=py[i-1]+1;
}
else
{
px[i]=px[i-1];
py[i]=py[i-1]-1;
}
}
int haha=check(1,n);
if(haha==1)
{
cout<<"-1";
return 0;
}
int L=0,R=n;
while(L<R)
{
int mid=(L+R)/2;
bool ansend=ok(mid);
if(ansend)
R=mid;
else
L=mid+1;
}
cout<<R;
return 0;
}