题目描述
n 个人围成一圈,从第一个人开始报数,数到 mm 的人出列,再由下一个人重新从 11 开始报数,数到 mm 的人再出圈,依次类推,直到所有的人都出圈,请输出依次出圈人的编号。
输入格式
输入两个整数 n,m,1<=m, n<=10。
输出格式
输出一行 n 个整数,按顺序输出每个出圈人的编号。
输入样例:10 3
输出样例 3 6 9 2 7 1 8 5 10 4
动态链表解法
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
struct node{
int data;
node *next;
};
int main()
{
int n,m;
scanf("%d %d",&n,&m);
node *head, *p,*now,*prev;
head =new node; head->data=1;head->next=NULL;
now=head;
for(int i=2;i<=n;i++)
{
p=new node;
p->data=i;
p->next=NULL;
now->next=p;
now=p;
}
now->next =head;
//约瑟夫环问题解法
now=head,prev=head;
while((n--)>1)
{
for (int i = 1; i < m; i++)
{
prev=now;
now=now->next;
}
printf("%d ",now->data);
prev->next=now->next;
delete now;
now=prev->next;
}
printf("%d",now->data);
delete now;
return 0;
}
STL解法
#include <iostream>
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n,m;
cin>>n>>m;
list<int>node;
for(int i=1;i<=n;i++)
{
node.push_back(i);
}
list<int>::iterator it= node.begin();
while(node.size()>1)
{
for(int i=1;i<m;i++)
{
it++;
if (it == node.end())
{
it =node.begin();
}
}
cout << *it<< " ";
list <int>::iterator next= ++it;
if(next == node.end())
{
next=node.begin();
}
node.erase(--it);
it=next;
}
cout << *it;
return 0;
}