题目:一个循环的圈,由两个人从头尾开始查找,分别将第m,第n的人删除,(两人是同时进行的),即是数完了才删除的,遇到相同的只输出一个,否则都输出,然后重新开始数,直至全部输完
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <cstring>
using namespace std;
const int MAXN = 25;
int N,pos1,pos2,m,n;
int prev[MAXN];
int next[MAXN];
void remove(int n)
{
next[prev[n]] = next[n];
prev[next[n]] = prev[n];
}
void init()
{
memset(next,0,sizeof(next));
memset(prev,0,sizeof(prev));
for(int i = 1 ; i<= N ;i++)
{
next[i] = i+1;
prev[i] = i-1;
}
next[N] = 1;
prev[1] = N;
pos1 = 1 ;
pos2 = N;
}
void solve()
{
while(1)
{
if(next[pos1] == pos1 || prev[pos2] == pos2) // 只剩下一个的情况
{
printf("%3d\n",pos1);
break;
}
int stepn = 1 ;
while(stepn++ < m )
pos1 = next[pos1];
stepn = 1;
while(stepn++ < n)
pos2 = prev[pos2];
if(pos1 == pos2 )
{
printf("%3d,",pos1);
int newpos1 = next[pos1];
int newpos2 = prev[pos2];
if(newpos1 == pos2)
newpos1 = next[newpos1];
if(newpos2 == pos1)
newpos2 = prev[newpos2];
remove(pos1);
pos1 = newpos1;
pos2 = newpos2;
}
else
{
int nnewpos1 = next[pos1];
int nnewpos2 = prev[pos2];
if(nnewpos1 == pos2)
nnewpos1 = next[nnewpos1];
if(nnewpos2 == pos1)
nnewpos2 = prev[nnewpos2];
if(nnewpos1 == pos1) //只剩下两个的情况
{
printf("%3d%3d\n",pos1,pos2);
break;
}
if(nnewpos2 == pos2) // 同上
{
printf("%3d%3d\n",pos1,pos2);
break;
}
printf("%3d%3d,",pos1,pos2);
remove(pos1);
remove(pos2);
pos1 = nnewpos1;
pos2 = nnewpos2;
}
}
}
int main()
{
while(scanf("%d %d %d",&N,&m,&n) != EOF )
{
if(N==0 && n == 0 && m == 0)
return 0;
init();
solve();
}
return 0;
}