【华为】删数

题目描述

有一个数组a[N]顺序存放0~N-1,要求每隔两个数删掉一个数,到末尾时循环至开头继续进行,求最后一个被删掉的数的原始下标位置。以8个数(N=7)为例:{0,1,2,3,4,5,6,7},0->1->2(删除)->3->4->5(删除)->6->7->0(删除),如此循环直到最后一个数被删除。

输入描述:

每组数据为一行一个整数n(小于等于1000),为数组成员数,如果大于1000,则对a[999]进行计算。

输出描述:

一行输出最后一个被删掉的数的原始下标位置。

示例1

输入

复制

8

输出

复制

6
#include "stdio.h"
#include <math.h>
#include <vector>
#include <iostream>
using namespace std;

int main()
{
	int n;
	while (cin >> n)
	{
		vector<bool> visit(n, 0);
		int pos=0,step = 0;
		int sum = n;
		int ans = -1;
		while (sum > 0)
		{
			if (!visit[pos%n])
				step++;

			if (step % 3 == 0&&!visit[pos%n]) //kill
			{
				sum--;
				visit[pos%n] = 1;
			}

			if (sum == 0)
				ans = (pos % n);
			pos++;
			
		}
		cout << ans << endl;
	}
	
	return 0;
}

猜你喜欢

转载自blog.csdn.net/leetcodecl/article/details/83010766