东秦oj1233: 幸运儿(约瑟夫环)

1233: 幸运儿

描述

题目描述:

n 个人围成一圈, 并依次编号1~n,。从编号为1 的人开始,按顺时针方向每隔一人选出一个,剩下的人重新围成一圈,如此循环直到剩下两人,这剩下的两人就是幸运儿。如果你想成为最后两个幸运儿,请问开始时应该站在什么位置?(设3<=n<=50)

输入:

有多个测试序列。每行是开始时的人数n

输出:

第1 行是选出顺序,第2 行是两名幸运儿的开始位置(按升序排列),位置编号之间用一个空格分开。

样例输入

12
20
45

样例输出

2 4 6 8 10 12 3 7 11 5 
1 9
2 4 6 8 10 12 14 16 18 20 3 7 11 15 19 5 13 9 
1 17
2 4 6 8 10 12 14 16 18 20 22 24 26 28 30 32 34 36 38 40 42 44 3 7 11 15 19 23 27 31 35 39 43 5 13 21 29 37 45 9 25 41 17 
1 33 

题解:

注意一下这道题每到结尾处,超过范围,就直接回到首点,而不是再数

#include<stdio.h>
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main()
{
	int n;
	while(scanf("%d",&n)!=EOF)
	{
		vector<int>vec;
		for(int i=0;i<n;i++)
		{
			vec.push_back(i+1);
		}
		int cnt=0;
		while(n>2)
		{
			cnt++;                   //这里隔一个数一个是从自身开始数2个数,但是由于删去一个数以后vector数组中的元素会往前移一位,所以只需要加2-1=1
			if(cnt>n-1) 
			{
				cnt=0;
				 continue;
			}
			else cnt%=n;   
			//if(n>3)
			printf("%d ",vec[cnt]);
			//else printf("%d\n",vec[cnt]);
			vec.erase(vec.begin()+cnt);
			n--;
			
		}
		printf("\n");
		printf("%d %d\n",vec[0],vec[1]);
		
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_40816078/article/details/81071471