1 //.h
2
3 #pragma once
4 #include <iostream>
5 using namespace std;
6 #define MAXSIZE 100
7
8 template <class T>
9 class SeqList
10 {
11 T data[MAXSIZE];
12 int length;
13 public:
14 SeqList();
15 SeqList(T a[],int n);
16 ~SeqList();
17 void Josephus2(int p[], int m0);
18 void PrintList();
19 };
20
21
22 template <class T>
23 SeqList<T>::SeqList()
24 {
25 length = 0;
26 }
27
28 template<class T>
29 SeqList<T>::SeqList(T a[], int n)
30 {
31 length = n;
32 for (int i = 0; i < length; i++)
33 data[i] = a[i];
34 }
35
36 template <class T>
37 SeqList<T>::~SeqList()
38 {
39 }
40
41 template<class T>
42 void SeqList<T>::Josephus2(int p[], int m0)
43 {
44 int k = 1;
45 int m = m0;
46 cout << " 出圈顺序为:" << endl;
47 while (length != 0)
48 {
49 k--;
50 int i = (k + m - 1) % length;
51 cout << data[i] << " ";
52 m = p[i];
53 for (int j = i; j < length - 1; j++)
54 {
55 data[j] = data[j + 1];
56 p[j] = p[j + 1];
57 }
58 length--;
59 k = i + 1;
60 }
61 cout << endl;
62 }
63
64 template<class T>
65 void SeqList<T>::PrintList()
66 {
67 for (int i = 0; i < length; i++)
68 cout << data[i] << " ";
69 cout << endl;
70 }
71
72
73
74 // 约瑟夫问题 密码不同.cpp : 定义控制台应用程序的入口点。
75 //主函数
76
77 #include "stdafx.h"
78 #include "SeqList.h"
79 #include <iostream>
80 using namespace std;
81
82 int main()
83 {
84 int a[6] = { 1,2,3,4,5,6 };
85 int b[6] = { 1,2,3,4,5,6 };
86
87 SeqList<int> s(a,6);
88 s.PrintList();
89 s.Josephus2(b,3);
90
91 system("PAUSE");
92 return 0;
93 }
94
95
题目:约瑟夫环问题的一种描述是:编号为1,2,3,…,n的n个人按顺时针方向围坐一圈,每人手持一个密码(正整数)。一开始任选一个整数作为报数上限值,从第一人开始顺时针自1开始顺序报数,报到m时停止报数。报m的人出列,将它的密码作为新的m值,从他在顺时针方向上的下一个人开始重新从1报数,如此下去直到所有人全部出列为止。试设计程序实现之。
来源:https://www.cnblogs.com/gmy-bstwrld/p/6869257.html