UVA10940 Throwing cards away II数学规律+约瑟夫环
Posted tigerisland45
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了UVA10940 Throwing cards away II数学规律+约瑟夫环相关的知识,希望对你有一定的参考价值。
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
", f[n]);
return 0;
}
以上是关于UVA10940 Throwing cards away II数学规律+约瑟夫环的主要内容,如果未能解决你的问题,请参考以下文章
UVA - 10935:Throwing cards away I (简单模拟)
UVA - 10935:Throwing cards away I (简单模拟)