http://codeforces.com/problemset/problem/1073/C
题意:起始点为(0,0),给一段n长度的操作序列,求出在这序列中最小的需要改变的区间长度,能使它从(0,0)到(x,y)。
题解:先对x,y都做一下预处理求前缀和,即原始指令字符串对x,y的改变所作出的贡献。二分区间长度,并检查这个长度是否能够满足题意,利用前缀和计算出理论上该区间x,y恰好所需的改变,然后怎样算满足题意呢?首先需要理论上所需的贡献值小于等于这个区间的长度,其次,区间t=长度-理论值应该是个偶数,因为t显然是多余的,所以剩下位的字符如果是偶数,那么就可以让其走的路程两两抵消,从而达到刚好到达终点的效果。
/*
*@Author: STZG
*@Language: C++
*/
#include <bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<cstdlib>
#include<cstring>
#include<cstdio>
#include<string>
#include<vector>
#include<bitset>
#include<queue>
#include<deque>
#include<stack>
#include<cmath>
#include<list>
#include<map>
#include<set>
//#define DEBUG
#define RI register int
#define endl "\n"
using namespace std;
typedef long long ll;
//typedef __int128 lll;
const int N=200000+10;
const int M=100000+10;
const int MOD=1e9+7;
const double PI = acos(-1.0);
const double EXP = 1E-8;
const int INF = 0x3f3f3f3f;
int t,n,m,k,p,x,y,l,r;
int ans,cnt,flag,temp,sum;
int a[2][N];
char str[N];
struct node{};
bool sloved(int mid){
for(int i=1;i+mid-1<=n;i++){
int l=i;
int r=i+mid-1;
int curx=a[0][l-1]+a[0][n]-a[0][r];
int cury=a[1][l-1]+a[1][n]-a[1][r];
int delta=abs(curx-y)+abs(cury-x);
if(delta<=mid&&(mid-delta)%2==0)return true;
}
return false;
}
int main()
{
#ifdef DEBUG
freopen("input.in", "r", stdin);
//freopen("output.out", "w", stdout);
#endif
//ios::sync_with_stdio(false);
//cin.tie(0);
//cout.tie(0);
//scanf("%d",&t);
//while(t--){
scanf("%d",&n);
scanf("%s",str+1);
scanf("%d%d",&x,&y);
if(n<abs(x)+abs(y)){
cout<<-1<<endl;
return 0;
}
for(int i=1;i<=n;i++){
a[0][i]=a[0][i-1];
a[1][i]=a[1][i-1];
if(str[i]=='U')a[0][i]++;
if(str[i]=='D')a[0][i]--;
if(str[i]=='L')a[1][i]--;
if(str[i]=='R')a[1][i]++;
}
l=0;
r=n;
ans=-1;
while(l<=r){
int mid=(l+r)>>1;
if(sloved(mid)){
ans=mid;
r=mid-1;
}else{
l=mid+1;
}
}
cout<<ans<<endl;
//}
#ifdef DEBUG
printf("Time cost : %lf s\n",(double)clock()/CLOCKS_PER_SEC);
#endif
//cout << "Hello world!" << endl;
return 0;
}