.acm 1373 light bubble

1373: C++通关考模拟题–Light bubble
Time Limit: 1 Sec Memory Limit: 128 MB
Submit: 2287 Solved: 465
[Submit][Status][Web Board]
Description
There are N lights in a empty room,numbering from 1 to N.The first person should turn all the lights on,and the second one should press those switches whose number is the multiple of 2 (those light will be turned off).And the third person should press those switches whose number is the multiple of 3 (the light on will be turned off,and the light off will be turned on).and so on.there K persons.
As a result ,which light will be on finally?

Input
There several test cases.
Every case includes N and K.(K<=N<=1000)

Output
Output all the numbers when the light is on.
There is a space between two different numbers.And there is a blank line between two different case.

Sample Input
4 2
6 2
Sample Output
1 3

1 3 5

#include<iostream>
#include<string>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
	int n,k;
	while (cin >> n >> k)
	{
		int*bub=new int[n+1];
		for (int i = 1; i <= n; i++)
			bub[i] = 1;//first person
		for (int p = 2; p <= k; p++)
		{
			for (int i = p; i <= n; i += p)
			{
				if (bub[i] == 0)bub[i] = 1;
				else {
					bub[i] = 0; 
				}
			}
		}
		int m = 0;
		for (int i = 1; i <=n; i++)
		{
			if (bub[i] != 0)
			{
				if (m== 0)cout <<i;
				else cout << ' ' <<i;
				m++;
		}
		}
		cout << endl;
		cout << endl;
		delete[]bub;
	}
}

第二种方法:使用bool类型数组:灯泡只有开关两种情况,用true,flase。每个人对灯泡变换操作:bub[i]=!bub[i];

#include<iostream>
#include<string>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
	int n,k;
	while (cin >> n >> k)
	{
		bool*bub=new bool[n+1];
		for (int i = 1; i <= n; i++)
			bub[i] = true;//first person
		for (int p = 2; p <= k; p++)
		{
			for (int i = p; i <= n; i += p)
			{
				bub[i] = !bub[i];
			}
		}
		int m = 0;
		for (int i = 1; i <=n; i++)
		{
			if (bub[i])
			{
				if (m == 0)cout <<i;
				else cout << ' ' <<i;
				m++;
		}
		}
		cout << endl;
		cout << endl;
		delete[]bub;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值