CodeForces - 1073C(二分)

題解:

二分區間長度,去尺取每一個區間,除去這段區間的操作量,判斷現操作距離目的操作所需步數與區間長度作對比,如果是偶數說明可以到達,否則不行。

#include <algorithm>
#include  <iostream>
#include   <cstdlib>
#include   <cstring>
#include    <cstdio>
#include    <string>
#include    <vector>
#include    <bitset>
#include     <stack>
#include     <cmath>
#include     <deque>
#include     <queue>
#include      <list>
#include       <set>
#include       <map>
#pragma comment(linker, "/STACK:1024000000,1024000000")
#define line printf("---------------------------\n")
#define mem(a, b) memset(a, b, sizeof(a))
#define pi acos(-1)
using namespace std;
typedef long long ll;
const double eps = 1e-9;
const int inf = 0x3f3f3f3f;
const int mod = 1e9+7;
const int maxn = 2000+10;

int n;
int aim_x, aim_y;
int now_x = 0, now_y = 0;
string s;

bool is_ok(int temp_x, int temp_y, int mid){
	int need_x = abs(aim_x-temp_x), need_y = abs(aim_y-temp_y);
	mid -= need_x;
	mid -= need_y;
	if(mid < 0){
		return false;
	}
	if(mid % 2 == 0){
		return true;
	}
	return false;
}

bool judge(int mid){
	int temp_x = 0, temp_y = 0;
	for(int i = 0; i < mid; i++){
		if(s[i] == 'U'){
			temp_y++;
		}
		if(s[i] == 'D'){
			temp_y--;
		}
		if(s[i] == 'L'){
			temp_x--;
		}
		if(s[i] == 'R'){
			temp_x++;
		}
	}
	if(is_ok(now_x-temp_x, now_y-temp_y, mid)){
		return true;
	}
	for(int i = 1; i+mid-1 < n; i++){
		if(s[i+mid-1] == 'U'){
			temp_y++;
		}
		if(s[i+mid-1] == 'D'){
			temp_y--;
		}
		if(s[i+mid-1] == 'R'){
			temp_x++;
		}
		if(s[i+mid-1] == 'L'){
			temp_x--;
		}
		if(s[i-1] == 'U'){
			temp_y--;
		}
		if(s[i-1] == 'D'){
			temp_y++;
		}
		if(s[i-1] == 'R'){
			temp_x--;
		}
		if(s[i-1] == 'L'){
			temp_x++;
		}
		if(is_ok(now_x-temp_x, now_y-temp_y, mid)){
			return true;
		}
	}
	return false;
}

int main(){
	cin>>n;
	cin>>s;
	cin>>aim_x>>aim_y;
	for(int i = 0; i < n; i++){
		if(s[i] == 'U'){
			now_y++;
		}
		if(s[i] == 'D'){
			now_y--;
		}
		if(s[i] == 'L'){
			now_x--;
		}
		if(s[i] == 'R'){
			now_x++;
		}
	}
	int l = 0, r = n, ans = -1;
	while(l <= r){
		int mid = (l+r) >> 1;
		if(judge(mid)){
			ans = mid;
			r = mid-1;
		}
		else{
			l = mid+1;
		}
	}
	printf("%d\n", ans);
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章