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.
Input
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. Input will not contain more than 500000 lines.
Output
For each number from input produce one line of output giving the last remaining card.
Sample Input
7
19
10
6
0
Sample Output
6
6
4
4
问题链接:UVA10940 Throwing cards away II
问题简述:(略)
问题分析:
????这个问题实际上是约瑟夫环问题,用数学规律来解才是王道,模拟法则会超时。可以用模拟法打印结果,寻找规律。打表是必要的,可以加速。
程序说明:(略)
参考链接:(略)
题记:(略)
AC的C++语言程序如下:
/* UVA10940 Throwing cards away II */
#include <bits/stdc++.h>
using namespace std;
const int N = 5e5;
int f[N + 1];
void init()
{
f[1] = 1;
int tmp = 1;
for(int i = 2; i <= N; i++) {
if(i > tmp * 2)
tmp *= 2;
f[i] = 2 * (i - tmp);
}
}
int main()
{
init();
int n;
while(~scanf("%d", &n) && n)
printf("%d\n", f[n]);
return 0;
}
原文地址:https://www.cnblogs.com/tigerisland45/p/10371592.html