UVa 1558 - Number Game

contents

  1. 1. Problem
  2. 2. Sample Input
  3. 3. Sample Output
  4. 4. Solution

Problem

給予 2 到 20 的內數字,兩名玩家輪流挑一個數字 x,並且將 x 的倍數遮蔽、x 倍數和已經被遮蔽的數字和也應該被遮蔽。

被遮蔽的數字將無法被使用。無法選擇任何數字的人輸。給定盤面上剩餘可選的數字,請問先手在第一步可以選擇哪幾個數字獲得勝利。

Sample Input

1
2
3
4
5
2
1
2
2
2 3

Sample Output

1
2
3
4
5
Scenario #1:
The winning moves are: 2.
Scenario #2:
There is no winning move.

Solution

由於數字量很小,可以進行 bitmask 壓縮,來得知數字的使用情況。接著套用博弈 dp 的思路,來得知必勝狀態!

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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#include <stdio.h>
#include <vector>
#include <string.h>
#include <algorithm>
using namespace std;
int dp[1<<20];
int pick(int state, int x) {
for (int i = x; i <= 20; i += x)
if ((state>>(i-2))&1)
state ^= 1<<(i-2);
for (int i = x; i <= 20; i++) {
if ((state>>(i-2))&1) {
if (i - x >= 2) {
if (((state>>(i - x -2))&1) == 0)
state ^= 1<<(i-2);
}
}
}
return state;
}
int dfs(int state) {
if (state == 0)
return 0;
if (dp[state] != -1)
return dp[state];
int &ret = dp[state];
ret = 0;
for (int i = 2; i <= 20; i++) {
if ((state>>(i-2))&1) {
int v = dfs(pick(state, i));
ret |= !v;
if (ret) break;
}
}
return ret;
}
int main() {
memset(dp, -1, sizeof(dp));
int testcase, cases = 0;
int n;
scanf("%d", &testcase);
while (testcase--) {
scanf("%d", &n);
int mask = 0, x;
for (int i = 0; i < n; i++) {
scanf("%d", &x);
mask |= 1<<(x-2);
}
printf("Scenario #%d:\n", ++cases);
vector<int> ret;
for (int i = 2; i <= 20; i++) {
if ((mask>>(i-2))&1) {
int v = dfs(pick(mask, i));
if (v == 0)
ret.push_back(i);
}
}
if (ret.size() == 0)
puts("There is no winning move.");
else {
printf("The winning moves are:");
for (int i = 0; i < ret.size(); i++)
printf(" %d", ret[i]);
puts(".");
}
puts("");
}
return 0;
}