题目链接:http://codeforces.com/problemset/problem/321/A
Ciel and Robot
Fox Ciel has a robot on a 2D plane. Initially it is located in (0, 0). Fox Ciel code a command to it. The command was represented by string s. Each character of s is one move operation. There are four move operations at all:
- 'U': go up, (x, y) → (x, y+1);
- 'D': go down, (x, y) → (x, y-1);
- 'L': go left, (x, y) → (x-1, y);
- 'R': go right, (x, y) → (x+1, y).
The robot will do the operations in s from left to right, and repeat it infinite times. Help Fox Ciel to determine if after some steps the robot will located in (a, b).
Input
The first line contains two integers a and b, ( - 109 ≤ a, b ≤ 109). The second line contains a string s (1 ≤ |s| ≤ 100, s only contains characters 'U', 'D', 'L', 'R') — the command.
Output
Print "Yes" if the robot will be located at (a, b), and "No" otherwise.
Examples
2 2
RU
Yes
1 2
RU
No
-1 1000000000
LRRLU
Yes
0 0
D
Yes
Note
In the first and second test case, command string is "RU", so the robot will go right, then go up, then right, and then up and so on.
The locations of its moves are (0, 0) → (1, 0) → (1, 1) → (2, 1) → (2, 2) → ...
So it can reach (2, 2) but not (1, 2).
思路:模拟一下,记录操作所能到达的所有点,以最后一个位置为一个循环。注意走向和坐标方向相反的情况。
附上AC代码:
#include <bits/stdc++.h>
//#pragma comment(linker, "/STACK:102400000, 102400000")
using namespace std;
const int maxn = 105;
char str[maxn];
int a, b;
vector<pair<int, int> > v;
int main(){
#ifdef LOCAL
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
#endif
while (~scanf("%d%d", &a, &b)){
getchar();
fgets(str, maxn, stdin);
int x=0, y=0;
if (x==a && y==b){
//printf("-1\n");
printf("Yes\n");
continue;
}
v.clear();
bool ok = true;
pair<int, int> t;
for (int i=0; str[i]!='\n'; ++i){
//printf("%c\n", str[i]);
if (str[i] == 'U')
++y;
else if (str[i] == 'D')
--y;
else if (str[i] == 'L')
--x;
else
++x;
if (x==a && y==b){
//printf("0\n");
printf("Yes\n");
ok = false;
break;
}
t.first = x;
t.second = y;
v.push_back(t);
}
if (ok){
bool f1=false, f2=false;
int n1=v[v.size()-1].first, n2=v[v.size()-1].second;
if (n1 != 0)
f1 = true;
if (n2 != 0)
f2 = true;
for (int i=0; i<v.size(); ++i){
//printf("%d %d\n", v[i].first, v[i].second);
int t1 = a-v[i].first;
int t2 = b-v[i].second;
if ((t1>0&&n1<=0) || (t2>0&&n2<=0) || (t1<=0&&n1>0) || (t2<=0&&n2>0))
continue;
if (f1){
if (t1%n1 == 0){
int k = t1/n1;
if (f2 && t2%n2==0 && t2/n2==k){
ok = false;
//printf("1\n");
break;
}
else if (!f2 && t2==0){
ok = false;
//printf("2\n");
break;
}
}
}
else{
if (t1 == 0){
if (f2 && t2%n2==0){
ok = false;
//printf("3\n");
break;
}
else if (!f2 && t2==0){
ok = false;
//printf("4\n");
break;
}
}
}
}
if (!ok)
printf("Yes\n");
else
printf("No\n");
}
}
return 0;
}