Josephus 排列问题

Josephus 排列问题定义如下:假设 n 个竞赛者排成一个环形。给定一个正整数 m,从某
个指定的第 1 个人开始,沿环计数,每遇到第 m 个人就让其出列,且计数继续进行下去。这
个过程一直进行到所有的人都出列为止。       最后出列者为优胜者。  每个人出列的次序定义了整
数 1,2,...,n 的一个排列。这个排列称为一个(n,m)Josephus

利用c++中的list来做 实验文件夹内容(input.txt):
5    2
hjs1
wcl2
zf3
ap4
zz5
(output.txt :)
1 : ap4
2 : wcl2
3 : hjs1
4 : zf3
5 : zz5
数到k是此人出局:
k = 3

原文件代码:
/* * ===================================================================================== * * Filename: Josephus.cpp * * Description: * * Version: 1.0 * Created: 2010年05月02日 23时45分14秒 * Revision: none * Compiler: gcc/linux * * Author: hjs-wcl (), [email protected] * Company: www.hjs-wcl.com.cn * * ===================================================================================== */ #include #include #include #include #include #include using namespace std; int main(int argc, char *argv[]) { int n; //总共有n个人 int m; //从m个人开始数 int k; //数到k时这个人出局 下个人数1 ifstream fin("input.txt", ios::in); //输入 n m 姓名的文件 ofstream fout("output.txt", ios::out);//输出出局顺序的文件 list obj; fin >> n; //获取总人数 fin >> m; //获取从何人开始 fin.ignore(3, '/n'); //忽略换行符 cout << "输入数到何数的时候那人出局 : "; cin >> k; for (int i = 0; i < n; ++i) { string str = ""; fin >> str; obj.push_back(str); fin.ignore(1, '/n'); //每行都有换行 故每行也要忽略一个换行符 } /*------end of for------*/ fin.close(); //copy(obj.begin(), obj.end(), ostream_iterator(cout, "/n")); //开始做出局工作 list::iterator pos = obj.begin(); //从第一个人开始 //转到第m个人 for (int i = 1; i < m; ++i) { ++pos; } /*------end of for------*/ int flog = 1; //标记出局的顺序 while (!obj.empty()) { for (int i = 1; i < k; ++i) { if (pos == obj.end()) { pos = obj.begin(); } ++pos; } /*------end of for------*/ //如果转到了结尾(pos=list.end()会是无效的须转到第一个人) if (pos == obj.end()) { pos = obj.begin(); } //把出局的人输入到文件中 fout << flog++ << " : " << *pos << endl; pos = obj.erase(pos); //此人出局 } /*------end of while------*/ fout.close(); } /*------end of main------*/

你可能感兴趣的:(linux,C开发)