codeforces B. Cat Cycle c++

B. Cat Cycle

Suppose you are living with two cats: A and B. There are n napping spots where both cats usually sleep.
Your cats like to sleep and also like all these spots, so they change napping spot each hour cyclically:
Cat A changes its napping place in order: n,n−1,n−2,…,3,2,1,n,n−1,… In other words, at the first hour it’s on the spot n and then goes in decreasing order cyclically;
Cat B changes its napping place in order: 1,2,3,…,n−1,n,1,2,… In other words, at the first hour it’s on the spot 1 and then goes in increasing order cyclically.
The cat B is much younger, so they have a strict hierarchy: A and B don’t lie together. In other words, if both cats’d like to go in spot x then the A takes this place and B moves to the next place in its order (if x<n then to x+1, but if x=n then to 1). Cat B follows his order, so it won’t return to the skipped spot x after A frees it, but will move to the spot x+2 and so on.
Calculate, where cat B will be at hour k?
两只小猫A和B,有n个窝,A猫按n,n-1,…2,1,n,n-1,n-2…的顺序挪窝,B猫按1,2…n-1,n,1,2,…,n的顺序挪窝,每小时挪一次。若两猫相遇,B猫会挪到下一个位置。问:在第k小时B猫在哪?
The first line contains a single integer t (1≤t≤1e4) — the number of test cases.
The first and only line of each test case contains two integers n and k (2≤n≤1e9; 1≤k≤1e9) — the number of spots and hour k.

输入样例

7
2 1
2 2
3 1
3 2
3 3
5 5
69 1337

输出样例

1
2
1
3
2
2
65

解题思路

分情况讨论,如果n是偶数就不会相遇,可以直接计算
如果是奇数易得每隔n-1/2个数就会挪一次窝
那么最后的位置就是挪窝次数加上k对n取模

AC代码

#include <iostream>
#include <cstring>
using namespace std;
int cx(int n,int i) {
    
    
	if(i%n==0)return 1;
	i%=n;
	return n-i+1;
}
int main() {
    
    
	int t;
	cin>>t;
	while(t--) {
    
    
		int n;
		cin>>n;
		if(n%2==0) {
    
    
			int k;
			cin>>k;
			k--;//这里减去一可以方便很多,可以仔细斟酌一下
			k%=n;
			cout<<++k<<endl;
		} else {
    
    
			int k;
			cin>>k;
			k--;
			int tt=n-1;
			int t1=tt/2;
			int ans1=k/t1;
			cout<<(ans1+k)%n+1<<endl;
		}
	}
}

猜你喜欢

转载自blog.csdn.net/qq_34832548/article/details/113832304