题目描述:
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?
Input
The first line contains a single integer t (1≤t≤104) — the number of test cases.
The first and only line of each test case contains two integers n and k (2≤n≤109; 1≤k≤109) — the number of spots and hour k.
Output
For each test case, print one integer — the index of the spot where cat B will sleep at hour k.
你与一只橘猫和一只波斯猫一起过着幸福的生活。你的家里有n个可供猫猫睡觉的地方。
你的猫喜欢在任何一个地方睡觉,所以它们会每小时周期性改变睡觉的地方:
· 橘猫按n, n-1, n-2, … , 3, 2, 1, n, n-1, …的顺序改变睡觉的位置;
· 波斯猫按1, 2, 3, … , n-1, n, 1, 2, … 的顺序改变睡觉的位置。
![](/qrcode.jpg)
橘猫的体型比波斯猫大得多,看起来非常可怕,所以当橘猫和波斯猫恰好想要睡到同一个地方时,波斯猫会让开位置,挪动到他的顺序的下一个位置。
k小时后,你的波斯猫在哪儿睡着?
Input
输入第一行有一个t,表示有t组输入。1 <= t <= 10000
接下来有t行,每一行有两个数,n和k。 2 <= n <= 1000000000; 1 <= k <= 1000000000
Output
输出t行,每一行一个整数,表示你的波斯猫的位置。
Example
Input
7
2 1
2 2
3 1
3 2
3 3
5 5
69 1337
Output
1
2
1
3
2
2
65
Note
In the first and second test cases n=2, so:
at the 1-st hour, A is on spot 2 and B is on 1;
at the 2-nd hour, A moves to spot 1 and B — to 2.
If n=3 then:
at the 1-st hour, A is on spot 3 and B is on 1;
at the 2-nd hour, A moves to spot 2; B’d like to move from 1 to 2, but this spot is occupied, so it moves to 3;
at the 3-rd hour, A moves to spot 1; B also would like to move from 3 to 1, but this spot is occupied, so it moves to 2.
In the sixth test case:
A’s spots at each hour are [5,4,3,2,1];
B’s spots at each hour are [1,2,4,5,2].
解题思路:
首先我们知道橘猫的位置都不会因为任何情况而改变,但是波斯猫会因为橘猫而改变,并且当位置的数量是偶数的时候波斯猫也不会改变,只是位置数量n为奇数的时候才会改变,并且通过查找规律我们发现,可以用n/2找出经过多少次换位置会出现一次相遇,因此我们就可以找到波斯猫走的总步数,然后用取模的方式来找出波斯猫最终的位置,废话不多说直接上代码:
#include <iostream>
#include <cstdio>
using namespace std;
int n,t,k;
int main () {
cin >> t;
while (t--) {
cin >> n >> k;
if(n%2 == 0)//偶数的情况
printf("%d\n",k%n ? k%n : n);//如果取模为0则波斯猫的位置为n,否则为n%k
else {
int a = n/2;//求出除了第一个位置外每次经过多少个位置会相遇
int m = (k-1)/a;//找到相遇的次数,即波斯猫少走的步数
int p = (m+k) % n;//用波斯猫的总步数来取模找到波斯猫的位置
if(p == 0)
cout << n << "\n";
else
cout << p << "\n";
}
}
return 0;
}