POJ 1781 In Danger

题目链接:http://poj.org/problem?id=1781

Sample Input

05e0
01e1
42e0
66e6
00e0

Sample Output

3
5
21
64891137

题解:Joseph(约瑟夫环)问题,模型是n个人,给定数字k,从第一个人开始,轮到第k个人,出列,再从第k+1人开始,再数k个人,一直循环到剩下最后一个........再讲讲这道题意,也是n个人,k为2,是一种特殊情况,所以有特殊解法,先介绍一下特殊解法:列一下n从1到10的情况:
1 1
2 1
3 3
4 1
5 3
6 5
7 1
8 3
9 5
10 7
可以看出答案是一个奇数排列,1 1,3 1,3,5 ....可以找出规律是先根据n找出这是第几个排列,然后再找出是在这个排列的第几个就行,一般解法会有另外一道题来说明。

#include <iostream>
#include<cstring>
#include<math.h>
#include<cstdio>
using namespace std;
//int queue[100000]={0};
int Josephu(long long a)
{int b=1;
for(int i=1;;i++)
{if(b>=a)
{
return 2*a-1;
break;
}
else
{
    a=a-b;
    b*=2;
}

}
return 0;
}
int main()
{char ch[10];
char p[10]="00e0";
scanf("%s",ch);
long long ans,num,mid;
while(strcmp(ch,p)!=0)
{
    num=(ch[0]-'0')*10+ch[1]-'0';
    mid=pow(10,ch[3]-'0');
    num*=mid;
    //cout<<num<<endl;
    if(num==1) ans=1;
    else
    ans=Josephu(num);
    printf("%lld\n",ans);
    scanf("%s",ch);
}
    return 0;
}
posted @ 2013-08-13 11:17  Qioayang,Allan,Zheng  阅读(265)  评论(0)    收藏  举报