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

来源:互联网 发布:淘宝飞鸽电动车怎么样 编辑:程序博客网 时间:2024/05/17 08:17
总时间限制(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 0
原创粉丝点击