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;
}
}