10940 - Throwing cards away II
Time limit: 3.000 seconds
Given is an ordered deck of n cards numbered 1 to n with card 1 at the top and card n at the bottom. The following operation is performed as long as there are at least two cards in the deck:
Throw away the top card and move the card that is now on the top of the deck to the bottom of the deck.
Your task is to find the last, remaining card.
Each line of input (except the last) contains a positive number n ≤ 500000. The last line contains 0 and this line should not be processed. For each number from input produce one line of output giving the last remaining card. Input will not contain more than 500000 lines.
Sample input
7 19 10 6 0
Output for sample input
6 6 4 4
思路请参考《具体数学》
完整代码:
/*0.039s*/
#include<cstdio>
int main()
{
int n, tmp, cnt, ans;
while (scanf("%d", &n), n)
{
cnt = 0;
for (tmp = n; tmp; tmp >>= 1) ++cnt;
ans = (n - (1 << (cnt - 1))) << 1;
printf("%d\n", ans ? ans : n);
}
return 0;
}

本文介绍了一种基于扔牌规则的算法实现,该算法通过特定操作来找出一副有序纸牌中最后剩下的那张牌。文章提供了完整的C++代码示例,并采用位运算优化算法效率。
720

被折叠的 条评论
为什么被折叠?



