约瑟夫问题(Josephus Problem)

转载

  1. http://maskray.me/blog/2013-08-27-josephus-problem-two-log-n-solutions
  2. http://haoyuanliu.github.io/2016/04/18/Josephus/
/***************************
@coding: utf-8
@Time    : 2018/6/3
@Author  : A1058420631
@FileName: Josephus Problem
@Software: Clion
***************************/
#include<iostream>
#include<cstdio>
using namespace std;
typedef struct node {
	int data;
	node* next;
}cLinkList;
int main()
{
	cLinkList *head, *p, *s, *temp;
	int i=1, n, m;
	cin >> n >> m;

	head = new cLinkList;
	p = head;
	p->next = p;
	p->data = i;

	for (i = 2; i <= n; ++i)
	{
		s = new cLinkList;
		s->next = p->next;
		p->next = s;
		s->data = i;
		p = s;
	}
	p = head;
	while (n--)
	{
		for (i = 1; i < m - 1; ++i)
			p = p->next;
		temp = p->next;
		if(n==0) cout << temp->data;
		p->next = temp->next;
		delete temp;
		p = p->next;
	}
	return 0;
}

纠错:链接2 未考虑n<m的情况 去掉m%=n 即可

猜你喜欢

转载自blog.csdn.net/a1058420631/article/details/80558847