3, Joseph problems (10 points)
Title Contents:
There are n monkeys, clockwise circle selected King (numbered from 1 to n), the number of newspaper from start No. 1, has been the number m, m number of monkeys to exit out of the loop, and then the rest of the monkeys then count off from the beginning. In this way, until the circle when only a monkey, the monkey is a monkey, seeking programming input n, the m, the number of output of the last monkey.
Input formats:
Input contains two integers, the first one is n, the second is m (0 <m, n <= 300).
Output formats:
The output contains one line, and last Monkey King number.
Sample input: 182
Sample output: 5
Time limit: 500ms Memory Limit: 32000kb
Ideas: involving the deletion of nodes and operating loop through the data, I used dual circulation list for data storage and processing.
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cstring>
using namespace std;
void solution();
//定义双循环链表节点
typedef struct Node
{
int number;
struct Node *next;
struct Node *prev;
Node()
{
number = 0;
prev = next = NULL;
}
Node(int n)
{
number = n;
prev = next = NULL;
}
} Node;
//定义猴子序列的双循环链表类
class MonkeyList
{
private:
Node *head;
Node *rear;
int len;
//将序号为num的元素从链表中删除,即被淘汰
bool remove(int num)
{
Node *p = head;
do
{
if (p->number == num)
{
p->prev->next = p->next;
p->next->prev = p->prev;
if (p == head)
{
head = p->next;
}
if (p == rear)
{
rear = p->prev;
}
delete p;
len--;
// cout << num << " has been deleted." << endl;
return true;
}
p = p->next;
} while (p != head);
return false;
}
public:
MonkeyList()
{
len = 0;
head = rear = NULL;
}
MonkeyList(int l)
{
len = l;
if (len == 0)
{
head = rear = NULL;
return;
}
head = new Node(1);
rear = head;
for (int i = 2; i <= len; i++)
{
Node *node = new Node(i);
node->next = head;
head->prev = node;
rear->next = node;
node->prev = rear;
rear = rear->next;
}
}
//依次报数,报到m的被删除
void countOff(int m)
{
Node *p = head;
int i = 1;
while (len > 1)
{
if (i == m)
{
Node *tmp = p->next;
remove(p->number);
p = tmp;
i = 1;
continue;
}
p = p->next;
i++;
}
cout << head->number << endl;
}
};
int main()
{
int T = 0;
int t = 0;
T = 1;
while (t < T)
{
solution();
t++;
}
system("pause");
return 0;
}
void solution()
{
int m, n;
cin >> n >> m;
MonkeyList *list = new MonkeyList(n);
list->countOff(m);
}