Description
将n个孩子从1到n 编上号,按序号围坐成一个圈,从s 号孩子开始数,每数到m 时,被数到的孩子即离开圈子,然后从下一个孩子开始,再从s+1 开始数,如此不断地数下去,只到只剩下最后一个孩子,问剩下的孩子是几号?
Input
输入为一个整数,每个整数占一行,第一个整数表示n ,即孩子的个数,第二整数表示s ,即从第几个孩子开始报数,第二个整数表示m ,即被数到m 的孩子将离开。
0<n<100, s>0 ,m>0.
0<n<100, s>0 ,m>0.
Output
被点到孩子依次输出,最后一个就是留下的 。
Sample Input
10
5
4
5
4
Sample Output
8
2
6
1
7
4
3
5
10
9
2
6
1
7
4
3
5
10
9
虽然这题很水,但为了纪念自己头一次模拟双向链表,还是写了吧!!........
代码:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <cstdio>
#include <cstdlib>
using namespace std;
struct point
{
int pre;//前指针
int next;//后指针
}child[105];
int main()
{
int n,s,m;
cin >> n >> s >> m;
for(int i=1; i<n; i++)//前后指针初始化
{
child[i].next = i+1;
}
child[n].next = 1;
for(int i=2; i<=n; i++)
{
child[i].pre = i-1;
}
child[1].pre = n;
int temp=0;
while(child[s].next != s)//当指向自己时即为结束
{
temp++;
if(temp == m)//数到m了
{
temp=0;
printf("%d\n",s);
child[child[s].next].pre = child[s].pre;//将s从链表中剔除
child[child[s].pre].next = child[s].next;//
}
s=child[s].next;//s下一个数
}
printf("%d\n",s);
return 0;
}