约瑟夫环 (Ver. I - A)
程序员文章站
2022-05-20 13:15:27
...
题目描述
N个人坐成一个圆环(编号为1 - N),从第S个人开始报数,数到K的人出列,后面的人重新从1开始报数。问最后剩下的人的编号。
例如:N = 3,K = 2,S = 1。2号先出列,然后是1号,最后剩下的是3号。
要求使用循环链表实现。
输入
测试数据有多组,
每组包括3个数N、K、S,表示有N个人,从第S个人开始,数到K出列。(1 <= N <= 10^6,1 <= K <= 10, 1 <= S <= N)
输出
出列的人的编号
样例输入
13 3 1 3 2 1
样例输出
3 6 9 12 2 7 11 4 10 5 1 8 13 2 1 3
#include <iostream>
#include <algorithm>
#define ok 0
#define error -1
using namespace std;
struct Node
{
int data;
Node *next;
Node(int _data=0, Node *_next=NULL):data(_data),next(_next){}
};
Node *createlist(int n,int *data)
{
Node *head = new Node;
Node *s,*tail=head;
for(int i=0; i<n; i++)
{
s = new Node(data[i],NULL);
tail->next = s;
tail = s;
}
tail->next=head;
return head;
}
void test(int u)
{
Node *head,*temp;
int k,*data,n=u,s;
cin>>k>>s;
data = new int[n];
for(int i=0;i<n;i++)
{
data[i]=i+1;
}
head = createlist(n,data);
Node *p=head,*q=head,*z=head;
int w=s,num=1,x=0;
while(w--)
{
p=p->next;
}
while(1)
{
if(q->next==p)
break;
else
q=q->next;
}
while(1)
{
if(p==head)
{
p=p->next;
q=q->next;
continue;
}
if(num==k)
{
cout<<p->data<<" ";
q->next=p->next;
z=p;
p=p->next;
free(z);
x++;
if(x==n)
break;
num=(num%k)+1;
}
else
{
p=p->next;
q=q->next;
num=(num%k)+1;
}
}
cout<<endl;
}
int main()
{
int n;
while(cin>>n)
{
test(n);
}
return 0;
}
上一篇: 栈---下一个更大元素