约瑟夫环-源码

#include <iostream>

using namespace std;

typedef struct Node
{
	int num,pwd;//num为人员编号,pwd为人眼所处位置的值
	struct Node *next;
}LNode, *LinkList;

void main()
{ 
	int i=1,m,n,j;//m为报数上限值,n为人数,j为输入的密码;   
	cout<<"please enter m:";
	cin>>m;   
	cout<<"please enter n:";
	cin>>n; 

	LinkList head,p,pt;

	while(i<=n)   
	{ 
		pt=new Node;  
		if(i==1)  
		{   
			p=head=pt;     
			cout<<"please enter the value:";   
			cin>>j;   
			p->num=i;   
			p->pwd=j;  
			i++;  
		}
		else  
		{	
			p->next=pt;     
			p=pt; 
			cout<<"please enter the value:"; 
			cin>>j;   
			p->num=i;   
			p->pwd=j;   
			i++;   
		} 
	}

	p->next=head;   
	for(i=1;i<=n;i++) 
	{  
		LinkList pd = new Node;
		for(int a=1;a<m;a++) 
			p=p->next;  
		pd=p->next;  
		m=pd->pwd;   
		cout<<m<<"\t"<<pd->num<<endl;		 
		p->next=pd->next;   
		free(pd); 
	}

	cout<<'\n';
}
这是一种方法,此种方法比较传统,不过比较全面,既可以输出序列,也可以输出序列所对应的值(当值和编号不同时尤其重要);另外有一种比较灵巧的算法,如下:
#include <stdio.h>
int main()
{
    int n, m, s = 0;
    printf ("N M = ");
    scanf("%d%d", &n, &m);
    for (int i = 2; i <= n; i++)
    {
        s = (s + m) % i;
    }
    printf ("\nThe winner is %d\n", s+1);
}

n个人,数到m跳出,从第一个人开始数;求最后的胜出者;

具体作者不明,可以参考:http://www.cnblogs.com/EricYang/archive/2009/09/04/1560478.html

  

posted on 2013-10-08 12:52  雪 狼  阅读(218)  评论(0编辑  收藏  举报

导航