链接:https://www.nowcoder.com/acm/contest/89/I
来源:牛客网
题目描述
Mr.Frog is researching integers.
He converts two integers X and Y into binary system without leading zeros, if they have the same quantity of 0 and the same quantity of 1 in the binary system, Mr.Frog will think these two integers are friendly.
For example, 5(10) = 101(2) and 6(10) = 110(2), both of them have two 1 and one 0 in the binary system, so Mr.Frog thinks 5 and 6 are friendly.
Now, Mr.frog gets an integer N and defines a sorted set S. The sorted set S consists of integers which are friendly with N and bigger than N. He wants to know what is the Kth integer in S.
Because Mr.Frog is on his way back from Hong Kong to Beijing, he wants to ask you for help.
输入描述:
The first line contains an integer T, where T is the number of test cases. T test cases follow.
For each test case, the only line contains two integers N and K.
• 1 ≤ T ≤ 200.
• 1 ≤ N ≤ 1018.
• 1 ≤ K ≤ 1018
输出描述:
For each test case, print one line containing “Case #x: y”, where x is the test case number (startingfrom 1) and y is the Kth integer in the sorted set S. If the integer he wants to know does not exist, y is“ IMPOSSIBLE”.
示例1
输入
2
9 2
7 4
输出
Case #1: 12
Case #2: IMPOSSIBLE
备注:
For the first case, the sorted set S is {10, 12}, so the 2nd integer is 12.
For the second case, the sorted set S is ∅, so the answer is “IMPOSSIBLE”.
昨天参加了浙财的校赛,感觉这题挺有意思的。
题目大概是说要将一个数转为二进制,然后看一下有几个0和1,再找一个下一个比他大的二进制数,要求0和1的数量要和前者相同。
这个题我在想的时候突然想笑出来,因为联想到了毛毛虫哈哈哈。一串二进制数字比如说10011000111
,怎么去找比他大的下一个数呢?因为有要求0和1的个数要相同,就可以向前移动他的1来得到符合要求的数,但如果一直抓住这串数中最后的一个1向前移动,是无法得到所有的组合的,然后我就想到了一种很好玩的移动方法。
每次移动的时候,把串中最后一串1作为一个毛毛虫,毛毛虫的头开始向前移动,然后是下一节的1移动,只要每次选择最后一串1的第一个1向前移动一格就行了。(一个1也要认为是一串1),这样就可以得到升序的所有符合要求的排列了。
10011000111
10011001011
10011001101
10011001110
10011010110
10011011010
10011011100
10011101100
10011110100
10011111000
算了不爬了,毛毛虫累了,这边可以算出总共可以爬几次,只要数一下每个0后面有几个1,将每个0后面的1的个数加起来就是总共可以爬的次数了。
AC代码呢?不存在的