1 //=====================================
2 // f1101.cpp
3 // josephus problem procedural solving
4 //=====================================
5 #include<iostream>
6 using namespace std;
7 //-------------------------------------
8 struct Jose{ // 小孩结点
9 int code; // 小孩编号
10 Jose* next; // 指向下一个小孩结点
11 };//-----------------------------------
12 int n, s, m;
13 Jose *pCur, *pivot;
14 //-------------------------------------
15 bool getValue();
16 Jose* createRing(); // 创建环链表
17 void countBoy(int m); // 数m个小孩
18 void process(); // 排除n-1个小孩
19 //-------------------------------------
20 int main(){
21 if(!getValue()) return 1;
22 Jose* pJose = createRing();
23 process();
24 cout<<"\nThe winner is "<<pCur->code<<"\n";
25 delete[] pJose;
26 getchar();
27 getchar();
28 }//------------------------------------
29 bool getValue(){
30 cout <<"please input boyNumber, startPosition, intervalNumber:\n";
31 cin>>n>>s>>m;
32 if(n>=2 && s>=1 && s<=n && m>=1 && m<=n) return true;
33 cerr<<"failed in bad boyNumber or startPosition or intervalNumber.\n";
34 return false;
35 }//------------------------------------
36 Jose* createRing(){
37 Jose* px = new Jose[n];
38 for(int i=1; i<=n; ++i){
39 px[i-1].next = &px[i%n];
40 px[i-1].code = i;
41 }//------------------------
42 cout<<"There are "<<n<<" boys.\nBoys leaved in order:\n";
43 pivot = &px[n-2];
44 pCur = &px[n-1];
45 countBoy(s-1);
46 return px;
47 }//------------------------------------
48 void countBoy(int m){
49 for(int i=0; i<m; ++i){
50 pivot = pCur;
51 pCur = pivot->next;
52 }
53 }//------------------------------------
54 void process(){
55 for(int i=1; i<n; ++i){
56 countBoy(m);
57 static int line=0;
58 cout<<" "<<pCur->code;
59 if(!(++line%10)) cout<<"\n";
60 pivot->next = pCur->next; //小孩脱链
61 pCur = pivot;
62 }
63 }//====================================