C++ 约瑟夫环问题
来源:互联网 发布:脸部表情软件 编辑:程序博客网 时间:2024/06/15 01:16
约瑟夫环是一个数学的应用问题:已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。
/*** 约瑟夫环:* 已知n个人(以编号1,2,3...n分别表示)围坐在一张圆桌周围。从编号为k的人开始报数,数到m的那个人出列;他的下一个人又从1开始报数,数到m的那个人又出列;依此规律重复下去,直到圆桌周围的人全部出列。* Josephu(int n, int m)* @author arhaiyun* Date: 2013-09-26**/#include "stdafx.h"#include <iostream>#include <stdlib.h>using namespace std;typedef struct LinkNode{int index;struct LinkNode* next;}JosephuNode;int Josephu(int n, int m){//[1].Create a circulatory Link listJosephuNode *head, *tail;head = tail = (JosephuNode*) malloc(sizeof(JosephuNode));;for(int i = 1; i < n; i++){tail->index = i;tail->next = (JosephuNode*)malloc(sizeof(JosephuNode));tail = tail->next;}tail->index = n;tail->next = head;//[1].Count to the specific number and let him outfor(int i = 1; tail != head; ++i){for(int j = 1; j < m; ++j){tail = head;head = head->next;}tail->next = head->next;cout<<"The "<<i<<" round "<<head->index<<" is out"<<endl;free(head);head = tail->next;}int winner = head->index;free(head);head = tail = NULL;return winner;}int main(){int winner = Josephu(5, 3);cout<<"Last winner is:"<<winner<<endl;system("pause");return 0;}
顺便附上一个数学思想的约瑟夫环解法,要求有点不一样。就是一共n个人,查到m的人出圈,求最后圈里的人是几号。
int fun(int n, int m){ int i, r = 0; for (i = 2; i <= n; i++) r = (r + m) % i; return r+1;}
- c之约瑟夫环问题
- C语言/约瑟夫环问题
- 【C语言】 约瑟夫环问题
- 约瑟夫问题、约瑟夫环
- 约瑟夫环问题 (c / c++)
- 约瑟夫环问题的C版本答案
- 约瑟夫环问题的C版本答案
- 约瑟夫环问题 数据结构 c语言
- 用c解决约约瑟夫环问题
- 约瑟夫环问题(Josephus)的C解法
- (C语言)约瑟夫环问题
- C语言实现约瑟夫环问题
- 约瑟夫问题求解(C++)
- 约瑟夫问题(c++)
- C语言求解约瑟夫问题
- 约瑟夫问题 C语言代码
- 数据结构 C语言 约瑟夫问题
- C 约瑟夫环
- Linux主要设备和名称
- VS2010下安装boost库
- oracle 常用调优手段
- 微信公众平台简单例子输出时间
- fopen,open的区别
- C++ 约瑟夫环问题
- 如何判断CPU是大端还是小端模式
- LeetCode - Remove Element
- WebRTC学习笔记_Demo收集
- 为什么要学习C语言?
- 表达式求值之递归下降
- linux daemon
- 非Oracle用户使用操作系统验证登陆(/ as sysdba)
- 百度质量部实习生面试