一群猴子要选新猴王。新猴王的选择方法是:让N只候选猴子围成一圈,从某位置起顺序编号为1~N号。从第1号开始报数,每轮从1报到3,凡报到3的猴子即退出圈子,接着又从紧邻的下一只猴子开始同样的报数。如此不断循环,最后剩下的一只猴子就选为猴王。请问是原来第几号猴子当选猴王?
输入格式:
输入在一行中给一个正整数N(≤1000)。
输出格式:
在一行中输出当选猴王的编号。
输入样例:
11
输出样例:
7
#include <iostream>
#include "algorithm"
#include <cstring>//可以用来清除数组
#include <cstdio>
using namespace std;
#include <string>
struct monkey{
int node;
struct monkey *next;
};
void test(struct monkey *head){
struct monkey *p;
p=head->next;
while (p!=NULL){
printf("%d",p->node);
p=p->next;
}
}
int main() {
int n;
scanf("%d",&n);
struct monkey *head;
struct monkey *tail;
struct monkey *p;//p是比较钱
struct monkey *pre;//pre是p的前端
head=(struct monkey*) malloc(sizeof (struct monkey));
head->node=-1;
head->next=NULL;
tail=head;
for (int i = 0; i < n; ++i) {//创建链表采用尾插发
p=(struct monkey*) malloc(sizeof (struct monkey));
p->node=i+1;
tail->next=p;
p->next=head->next;
tail=p;//这里设置有一个尾指针了,非常方便
}
p=head->next;
pre=tail;
int i=1;//开始报数了
while (p!=pre){
if(i%3==0){//找到推出的那个猴子了
pre->next=p->next;
free(p);
p=pre->next;
i++;//向前推进
} else{
p=p->next;
pre=pre->next;
i++;//如果没有找到那就向前推进
}
}
printf("%d",p->node);
free(p);
return 0;
}