您的位置:首页 > 其它

POJ3750: 小孩报数问题+一道经典约瑟夫问题(猴子选大王)

2014-12-30 19:55 323 查看
又一次因为一个小错误,POJ上Wrong Answer了无数次。。。。。

在差不多要放弃的时候,发现了这个猥琐的不能再猥琐的bug,改完了提交就AC了,简直无语。。。。

本题wo采用模拟方法:

1 #include<iostream>
2 #include<cstring>
3 #include<cstdio>
4 using namespace std;
5 struct child{
6     int name;
7     int id;
8     //child(string, int);
9 }cd[100];
10 void init(int n){
11     for(int i=1;i<=n;i++){
12         cd[i].name=i;
13         cd[i].id=0;
14     }
15 }
16 void solve(int n,int s){
17     init(n);
18     cd[1].id=1;
19     int pt=1;
20     int kill=0;
21     while(true){
22         int step=s%(n-kill)-1;
23         if(step<=0) step=step+n-kill;
24         /*
25             这里的取模运算是考虑到s值可能非常大,如果这样的话,模拟报数过程1。。。。s将会非常
26             耗时间。
27             至于为什么这么取模,自己算一算就明白了。
28         */
29         for(int i=1;i<=step;i++){
30                 int ptr=pt%n+1;
31                 while(cd[ptr].id==-1){//要跳过已经被kill的元素
32                     ptr=ptr%n+1;
33                 }
34                 cd[ptr].id=cd[pt].id+1;
35                 pt=ptr;
36         }//这里的pt指向的就是我们要删除的元素
37         cd[pt].id=-1;//将id赋值为-1,相当于删除动作
38         kill++;
39         if(kill==n){
40             printf("%d\n",cd[pt].name); break; //已经清空,跳出循环
41         }
42         int ptr=pt%n+1;
43         while(cd[ptr].id==-1){
44                     ptr=ptr%n+1;
45         }
46         cd[ptr].id=1;
47         pt=ptr;
48
49     }
50 }
51 int main(){
52          int n,s;
53         while(scanf("%d%d",&n,&s)!=EOF&&n&&s){
54             solve(n,s);
55         }
56         return 0;
57 }


View Code


                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: