循环链表-约瑟夫问题-猴子选大王

总时间限制(Time limit):
1000ms
内存限制(Memory limit):
65536kB
描述(Description)

有n只猴子,按顺时针方向围成一圈选大王(编号从1到n),从第1号开始报数,一直数到m,数到m的猴子退出圈外,剩下的猴子再接着从1开始报数。就这样,直到圈内只剩下一只猴子时,这个猴子就是猴王,编程求输入n,m后,输出最后猴王的编号。
There are n monkeys who surround in a circle to select their king (numbered from 1 to n). They count off from the first monkey until m. The monkey who counts m leaves the circle and then the left monkeys count off from 1 again. Keep like this, and there will be only one monkey in the circle at last. And this one is the monkey king. You are asked to output the serial number of the monkey given the input n and m. 

输入(Input)

输入包含两个整数,第一个是n,第二个是m (1<m,n<=300)。
The input contains two intergers. The first one is n and the second is m((1<m,n<=300).

输出(Output)

输出包含一行,即最后猴王的编号。
The output contains one line, the serial number of the monkey king.

样例输入(Sample input)

12 4

样例输出(Sample output)

1

<span style="font-size:14px;">#include <iostream>
using namespace std;

struct monkey
{
 int num;
 monkey *next;
};

int joseph(int sum, int cycle)
{
    int i;
    monkey *p_old, *p_new, *head=NULL;

    head = new monkey; 
//此处创建一个循环链表(create a circular chained table)
    head->num = 1;
    p_old = head;
    for(i=2; i<=sum; i++)
    {
        p_new = new monkey;
        p_new->num = i;

 		p_old->next = p_new;
 		p_old = p_new;
    }

	p_old->next = head; //把尾巴链接到 head 

    p_old = head; 
    i = 1;
//循环删除元素直到只剩下最后一个元素(delete elements circularly until the last element left)
    while(1)
    {
        p_new = p_old->next;
        i++;

        if ( p_old->num == p_new->num) //or if (sum == 1)
            break;
        if((i % cycle) == 0)
        {
  			p_old->next = p_new->next;
  			p_old = p_old->next;
//  		sum--;
            delete p_new;
            i = 1;
    	 }
        else
        {
            p_old = p_new;
        }
    }

    return p_new->num;
}

int main(void)
{
 	int n,m;
 	cout<<"How many monkeys are there? input the number(n): ";
  	cin>>n;

 	cout<<"What's the numebr you wanna call? input(m): ";
 	cin>>m;

 	cout<<"In this circumstance, the monkey king is the No.";
	cout << joseph(n,m)<<endl;
 	return 0;
}</span>


  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值