上周在机试,第三道是约瑟夫环问题。题目如下:
约瑟夫环问题的原来描述为,设有编号为1,2,……,n的n(n>0)个人围成一个圈,从第1个人开始报数,报到m时停止报数,报m的人出圈,再从他的下一个人起重新报数,报到m时停止报数,报m的出圈,……,如此下去,直到所有人全部出圈为止。当任意给定n和m后,设计算法求n个人出圈的次序。
下面给出最简单的程序:
#include <iostream>
#include <vector>
using namespace std;
struct Node
{
int flag;
int code;
Node* next;
};
Node* createlist(vector<int>a, int lenth)
{
Node* head = new Node;
head->flag = 1;
head->code = a[0];
Node* pnode = head;
Node* rear = new Node;
for (int i=1; i<lenth-1; i++)
{
Node* node = new Node;
node->flag = i+1;
node->code = a[i];
pnode->next = node;
pnode = node;
}
pnode->next = rear;
rear->flag = lenth;
rear->code = a[lenth-1];
rear->next = head;
return head;
}
void func(Node* node, int code)
{
if (!node)
{
return ;
}
if (node->next == node)
{
cout << node->flag;
return ;
}
Node* pnode = node;
for (int i=1; i<code-1; i++)
{
pnode = pnode->next;
}
cout << pnode->next->flag;
Node* node_delete = pnode->next;
int new_code = node_delete->code;
pnode->next = pnode->next->next;
delete (node_delete);
node_delete = NULL;
func(pnode->next, new_code);
}
int main()
{
int lenth,m;
vector<int> a_code;
cin>>lenth>>m;
for (int i=0; i<lenth; i++)
{
int code;
cin>>code;
a_code.push_back(code);
}
Node* head = createlist(a_code, lenth);
func(head, m);
return 0;
}