72个人,从第9个人开始报数,报到11的人退出,下一位继续从1开始报数,问最后一个人编号。
#include<iostream>
using namespace std;
const int NUM = 72;
struct node{
int value;
node* next;
};
void func()
{
int i;
node* head = new node;
head->value = 1;
node* pre = head;
for(i=1; i<NUM; i++)
{
node* n = new node;
n->value = i+1;
pre->next = n;
pre = n;
}
pre->next = head;
node* s = head;
while(s->value != 9)
s = s->next;
int count = NUM;
int flag_end = 11;
int flag_s = 1;
node** pp = &s;
while(count >1)
{
while(flag_s != flag_end)
{
flag_s++;
pp = &s->next;
s = s->next;
}
*pp = s->next;
delete s;
flag_s = 1;
s = *pp;
count--;
}
cout<<s->value;
}
int main()
{
func();
return 0;
}
另有一个简单方法:
int lastRemaining(int n, int m)
{
if(n<1 || m<1)
return -1;
int last = 0;
for(int i=2; i<=n; i++)
last = (last+m)%i;
return last;
}