Nim Game

Nim Game


You are playing the following Nim Game with your friend: There is a heap of stones on the table, each time one of you take turns to remove 1 to 3 stones. The one who removes the last stone will be the winner. You will take the first turn to remove the stones.

Both of you are very clever and have optimal strategies for the game. Write a function to determine whether you can win the game given the number of stones in the heap.

For example, if there are 4 stones in the heap, then you will never win the game: no matter 1, 2, or 3 stones you remove, the last stone will always be removed by your friend.

重要的是找出必胜状态与必败状态。

此类问题的正确描述在于注释内的代码,通过递推关系求出结果。

非注释代码只是根据题目取了巧,递推求结果会导致超时。

AC代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
class Solution {
public:

bool canWinNim(int n) {
/*
if ( n == 0 ) return false;
if ( n <= 3 ) return true;
vector<bool> stones(n,false);
stones[0] = stones[1] = stones[2] = true;
for (int i = 3; i < n ; ++i)
{
if (stones[i-1] && stones[i-2] && stones[i-3])
{
stones[i] = false;
}
else
{
stones[i] = true;
}
}
return stones[n-1];
*/

return !(n % 4 == 0);
}
};


Nim Sum


From: HiHoCoder #1163 博弈游戏·Nim游戏

Nim Sum的应用。

AC代码:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>
#include <vector>
using namespace std;

int main(int argc, char** argv)
{

int N = 0;
cin >> N;
if (N == 1)
{
cout << "Alice" << endl;
return 0;
}
int M = 0;
cin >> M;
int r = M;
for (int i = 1; i < N; ++i)
{
cin >> M;
r ^= M;
}
(r == 0) ? (cout << "Bob" << endl) : (cout << "Alice" << endl);

return 0;
}