uva 133

题目:一个循环的圈,由两个人从头尾开始查找,分别将第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;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值