首页 > 代码库 > UVA - 1500 Alice and Bob (dp+博弈)
UVA - 1500 Alice and Bob (dp+博弈)
Description
Alice and Bob are very smart guys and they like to play all kinds of games in their spare time. the most amazing thing is that they always find the best strategy, and that‘s why they feel bored again and again. They just invented a new game, as they usually did.
The rule of the new game is quite simple. At the beginning of the game, they write downN random positive integers, then they take turns (Alice first) to either:
- Decrease a number by one.
- Erase any two numbers and write down their sum.
Whenever a number is decreased to 0, it will be erased automatically. the game ends when all numbers are finally erased, and the one who cannot play in his(her) turn loses the game.
Here‘s the problem: Who will win the game if both use the best strategy? Find it out quickly, before they get bored of the game again!
Input
The first line contains an integer T(1T4000), indicating the number of test cases.
Each test case contains several lines.
The first line contains an integer N(1N50).
The next line contains N positive integers A1...AN(1Ai1000), represents the numbers they write down at the beginning of the game.
Output
For each test case in the input, print one line: `Case #X:Y‘, whereX is the test case number (starting with 1) andY is either "Alice" or "Bob".
Sample Input
3 3 1 1 2 2 3 4 3 2 3 5
Sample Output
Case #1: Alice Case #2: Bob Case #3: Bob 题意:有n个数,你可以把一个数减一,或者删掉两个数,然后记上它们的和,两个人轮流操作,不能操作的算输,Alice先手,求结果 思路:如果每堆石子数都大于1,那么最后结果肯定相当于所有的堆合并成一堆后,然后再一个一个拿掉的结果。 因为如果那种情况是赢的人一定会不断合并堆来确保他是赢的。又因为所有堆的石子数都大于1,所以输的人无法阻止他这么干。 而有些堆石子数等于1的话,就不一定是所有的合并的结果了,因为输的人可以直接把等于1的堆去掉,就破坏了结构 (合并相当于2步,去掉只需要1步)。 dp[i][j]表示有i个石子数为1的堆数,其它堆合并再取完的步数为j。若值为1则先取者胜,为0为先取者输。 那么就有这几种情况:将某堆只能1的拿走;两堆是1的合并;把不是1的减一;把某堆是1的并到不是1的堆上#include <iostream> #include <cstring> #include <algorithm> #include <cstdio> using namespace std; int dp[60][60000]; int dfs(int i, int j) { if (dp[i][j] != -1) return dp[i][j]; if (j == 1) return dp[i][j] = dfs(i+1, 0); dp[i][j] = 0; if (i >= 1 && !dfs(i-1, j)) dp[i][j] = 1; else if (j >= 1 && !dfs(i, j-1)) dp[i][j] = 1; else if (i >= 1 && j > 0 && !dfs(i-1, j+1)) dp[i][j] = 1; else if (i >= 2 && ((j >= 1 && !dfs(i-2, j+3)) || (j == 0 && !dfs(i-2, 2)))) dp[i][j] = 1; return dp[i][j]; } int main() { int t, n, tmp, cas = 1; scanf("%d", &t); memset(dp, -1, sizeof(dp)); dp[0][0] = 0; while (t--) { int a = 0, b = 0; scanf("%d", &n); for (int i = 0; i < n; i++) { scanf("%d", &tmp); if (tmp == 1) a++; else b += tmp + 1; } if (b) b--; printf("Case #%d: ", cas++); if (dfs(a, b)) printf("Alice\n"); else printf("Bob\n"); } return 0; }
UVA - 1500 Alice and Bob (dp+博弈)