题目:醉酒的狱卒
某监狱有一个由
n
个牢房组成的大厅,每个牢房紧挨着。每个牢房里都有一个囚犯,每个牢房都是锁着的。 一天晚上,狱
卒感到无聊,决定玩一个游戏。在第一轮,他喝了一杯威士忌,然后跑下大厅,打开每个牢房的锁。在第二轮比赛中,他
喝了一杯威士忌,然后跑下大厅,锁上每隔一个的牢房的锁(牢房
2
、
4
、
6....
)。在第三轮比赛中,他喝了一杯威士忌,
然后跑下大厅。他每隔三个牢房(第
3
、
6
、
9
号牢房)就去一次。如果牢房被锁上了,他就把它打开;如果牢房门打开
了,他就锁上牢房。他重复
n
轮,喝最后一杯,然后昏倒。 一些囚犯(可能为零号)意识到他们的牢房被解锁且狱卒丧失
了行动能力。他们就可以立即逃跑。现在根据牢房数量,确定有多少囚犯越狱。
解法:
#include <iostream>
using namespace std;
int solution(int n)
{
bool *room = new bool[n + 1];
for (int i = 0; i <= n; i++)
{
room[i] = false;
}
int count = 1;
while (count <= n)
{
for (int i = 0; i <= n; i += count)
{
room[i] = !room[i];
}
count++;
}
// 计算有多少
int result = 0;
for (int i = 1; i <= n; i++)
{
if (room[i] == true)
{
result++;
}
}
return result;
}
int main()
{
int t;
cin >> t;
for (int i = 0; i < t; i++)
{
int n;
cin >> n;
cout << solution(n) << endl;
}
return 0;
}