您的位置:首页 > 其它

约瑟夫问题(循环链表)

2015-06-07 19:14 363 查看

约瑟夫问题

Time Limit: 1000MS Memory limit: 65536K

题目描述

n个人想玩残酷的死亡游戏,游戏规则如下:

n个人进行编号,分别从1到n,排成一个圈,顺时针从1开始数到m,数到m的人被杀,剩下的人继续游戏,活到最后的一个人是胜利者。

请输出最后一个人的编号。

输入

输入n和m值。

输出

输出胜利者的编号。

示例输入

5 3


示例输出

4


提示

第一轮:3被杀第二轮:1被杀第三轮:5被杀第四轮:2被杀

#include<stdio.h>
#include<stdlib.h>
struct nobe
{
int data;
struct nobe*next;
}*p,*q,*head,*tail;
int main()
{
int n,m,i;
scanf("%d%d",&n,&m);
head=(struct nobe*)malloc (sizeof(struct nobe ));
p=head;
p->data=1;
p->next=NULL;
tail=p;
for(i=2;i<=n;i++)
{
p=(struct nobe*)malloc(sizeof(struct nobe));
p->next=NULL;
p->data=i;
tail->next=p;
tail=p;
}
tail->next=head;

int num=0;
int count=0;
p=head;
while(p->next!=head)
{
p=p->next;
}
while(count <n)
{
q=p->next;
num++;
if(num%m==0)
{
p->next=q->next;
count++;
}
else
p=q;
}
printf("%d\n",p->data);
return 0;
}


<pre name="code" class="cpp">#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cmath>
#include<queue>

using namespace std;

struct node
{
int data;
node *next;
}*head,*p,*tail,*q;
int main()
{
int n,m,i,j;
scanf("%d%d",&n,&m);
head=new node;
head->next=NULL;
tail=head;
head->data=1;
for(i=2;i<=n;i++)
{
p=new node;
p->next=NULL;
p->data=i;
tail->next=p;
tail=p;
}
tail->next=head;
//	printf("%d\n",tail->next->data);
int num=0,num1=1;
p=head;                    //<span id="transmark"></span>
while(num<n)
{
if(num1%m==0)
{
tail->next=p->next;
p=tail->next;
num1++;
num++;
}
else
{
tail=tail->next;
p=p->next;
num1++;
}
}
printf("%d\n",p->data);
}



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: