版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/C_13579/article/details/83662794
地址:http://codeforces.com/contest/1073/problem/C
思路:一开始做思路就错了,我考虑的是如何转变方向使其有效到达目标位置,但是比较复杂。这题要求更改的区间最小长度。因此可以二分区间长度,在遍历左端点看是否存在即可。判断存在,即更改的区间的个数是否能将其他区域的缺少或多余步骤给消掉即可。
Code:
#include<iostream>
#include<vector>
#include<cmath>
using namespace std;
const int MAX_N=2e5+5;
int n;
int x0,y0;
string str;
int px[MAX_N],py[MAX_N];
bool judge(int l,int r);
int main()
{
ios::sync_with_stdio(false);
while(cin>>n){
cin>>str;
cin>>x0>>y0;
for(int i=0;i<n;++i)
if(str[i]=='U') py[i+1]=py[i]+1,px[i+1]=px[i];
else if(str[i]=='D') py[i+1]=py[i]-1,px[i+1]=px[i];
else if(str[i]=='L') px[i+1]=px[i]-1,py[i+1]=py[i];
else if(str[i]=='R') px[i+1]=px[i]+1,py[i+1]=py[i];
int l=0,r=n,h;
while(l<=r){
h=(l+r)/2;
bool boo=false;
for(int i=1;i+h-1<=n;++i)
if(judge(i,i+h-1)){
boo=true; break;
}
if(boo) r=h-1;
else l=h+1;
}
if(l>n) l=-1;
cout<<l<<endl;
}
return 0;
}
bool judge(int l,int r)
{
bool boo=true;
int xi=px[l-1]+px[n]-px[r];
int yi=py[l-1]+py[n]-py[r];
int s0=abs(xi-x0)+abs(yi-y0),si=r-l+1;
if(si<s0||(si-s0)%2) boo=false;
return boo;
}