程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> 關於C++ >> uva 10404 Bachet's Game (完全背包+博弈)

uva 10404 Bachet's Game (完全背包+博弈)

編輯:關於C++

uva 10404 Bachet’s Game

Bachet’s game is probably known to all but probably not by this name. Initially there are n stones on the table. There are two players Stan and Ollie, who move alternately. Stan always starts. The legal moves consist in removing at least one but not more than k stones from the table. The winner is the one to take the last stone.

Here we consider a variation of this game. The number of stones that can be removed in a single move must be a member of a certain set of m numbers. Among the m numbers there is always 1 and thus the game never stalls.
Input
The input consists of a number of lines. Each line describes one game by a sequence of positive numbers. The first number is n <= 1000000 the number of stones on the table; the second number is m <= 10 giving the number of numbers that follow; the last m numbers on the line specify how many stones can be removed from the table in a single move.
Input
For each line of input, output one line saying either Stan wins or Ollie wins assuming that both of them play perfectly.
Sample input

20 3 1 3 8
21 3 1 3 8
22 3 1 3 8
23 3 1 3 8
1000000 10 1 23 38 11 7 5 4 8 3 13
999996 10 1 23 38 11 7 5 4 8 3 13

Output for sample input

Stan wins
Stan wins
Ollie wins
Stan wins
Stan wins
Ollie wins

題目大意:給出石頭的總數sum, 和取石頭的方法(一次能取多少石頭)n,接下來是n種取石頭的方式。在雙方都想贏的狀況下,問誰能最後拿走全部石頭(先手還是後手)。

解題思路:主體是完全背包的思路。dp數組有{0, 1}兩種狀況,1代表當前i個石頭先取者必勝,0代表當前i個石頭先取者必敗,狀態轉移方程是:dp[i?num[j]]==0??>dp[i]=1

#include 
#include 
#include 
#include 
#include 
#define N 1000005
#define M 15
using namespace std;
typedef long long ll;
int num[M], dp[N];
int main() {
    int sum, n; 
    while (scanf("%d %d", &sum, &n) == 2) {
        memset(dp, 0, sizeof(dp));
        for (int i = 0; i < n; i++) {
            scanf("%d", &num[i]);
        }
        for (int i = 1; i <= sum; i++) {
            for (int j = 0; j < n; j++) {
                if (i - num[j] >= 0 && !dp[i - num[j]]) { //該取石頭的方式可行 且 取完石頭之後剩余的石頭不能一次取完。
                    dp[i] = 1;
                    break;
                }
            }
        }
        if (dp[sum]) printf("Stan wins\n");
        else printf("Ollie wins\n");
    }
    return 0;
}
  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved