题意:
有两种走完闭环的方式,顺时针或者逆时针。给定环的长度,并分别给出两个人的起点和终点,问这两个人是否能在同一个点相遇。
思路:
1、找到两个人中最小的步数,因为如果可以相遇也是在最小的步数之内相遇。
2、对最小的步数开始进行操作,顺时针走的判断是不是走到了环的终点(最大值),如果是将下一步操作点置为起(1);如果不是,就递增。逆时针走的判断是不是走到了环的起点(1),如果是将下一步操作置为环的终点(最大值);如果不是,就递减。
3、没执行完一次操作,判断是不是相等(即相遇)。
代码如下:
#include<iostream>
using namespace std;
bool check(int n,int a,int x,int b, int y){
if(a!= x && a!= b && a!= y && x!= b && x!= y && x!=y){
//cout << "正常输入" << endl;
return true;
} else{
//cout << "异常输入" << endl;
return false;
}
}
int FirstStep(int n, int a, int x){
if(x > a){
//cout << "第一步 " << x-a << endl;
return x-a;
} else{
//cout << "第一步 " << n+x-a <<endl;
return n+x-a;
}
}
int SecondStep(int n, int b, int y){
if(b > y){
//cout << "第二步 " << b - y << endl;
return b-y;
} else{
//cout << "第二步 " <<b+n-y << endl;
return n+b-y;
}
}
int main() {
int n, a, x, b, y, step, tempA , tempB;
while(cin >> n >> a >> x >> b >> y){
if(!check(n, a, x, b, y)) return 0;
if(FirstStep(n,a,x) >= SecondStep(n,b,y)){
step = SecondStep(n,b,y);
} else{
step = FirstStep(n,a,x);
}
tempA = a;
tempB = b;
while(step != 0){
step--;
//cout << "开始a" << a << endl;
//cout << "开始b" << b << endl;
//第一辆车递增
if(a != n){
a++;
} else{
a = 1;
}
//第二辆车递减
if(b == 1){
b = n;
} else{
b--;
}
//cout << "a" << a << endl;
//cout << "b" << b << endl;
//运动结束后比较
if(a == b){
break;
}
}
if(a == b){
cout << "YES" << endl;
} else{
cout << "NO" << endl;
}
}
}