Hdu 4203 Doubloon Game 博弈+打表

来源:互联网 发布:单片机多路压力采集 编辑:程序博客网 时间:2024/06/05 15:29

Doubloon Game

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 713    Accepted Submission(s): 381


Problem Description
Being a pirate means spending a lot of time at sea. Sometimes, when there is not much wind, days can pass by without any activity. To pass the time between chores, pirates like to play games with coins.

An old favorite of the pirates is a game for two players featuring one stack of coins. In turn, each player takes a number of coins from the stack. The number of coins that a player takes must be a power of a given integer K (1, K, K^2, etcetera). The winner is the player to take the last coin(s).
Can you help the pirates gure out how the player to move can win in a given game situation?
 

Input
The first line of the input contains a single number: the number of test cases to follow. Each test case has the following format:
One line with two integers S and K, satisfying 1 <= S <= 10^9 and 1 <= K <= 100: the size of the stack and the parameter K, respectively.
 

Output
For every test case in the input, the output should contain one integer on a single line: the smallest number of coins that the player to move can take in order to secure the win. If there is no winning move, the output should be 0.
 

Sample Input
55 13 28 250 3100 10
 

Sample Output
10201
 

Source
BAPC 2011

一堆硬币n个,每次只能取k的若干次方个,问先手第一步最少取几个可以保证必胜。如果必败输出0.

博弈类题目。这题可以直接dfs求sg函数,但是数据范围太大,直接求解肯定会超时。

这时,可以打个表找规律。规律很容易发现。

打表程序如下:

#include <cstdio>#include <iostream>#include <vector>#include <string.h>#include <map>#include <algorithm>#include <set>#include <math.h>#include <cmath>#include <queue>using namespace std;typedef long long ll;int a[35];int getsg(int sum) {bool visit[1005];int i,f;memset(visit,0,sizeof(visit));for (i=1;i<=a[0];i++) {if (sum-a[i]>=0) {visit[f=getsg(sum-a[i])]=1;if (!f) return 1;}}for (i=0;;i++)    if (!visit[i]) return i;}int main() {int n,k,i,f;     //n和k的值可根据需要任意改动for (k=1;k<=15;k++) {for (n=k;n<=30;n++) {ll l=k;a[0]=1;a[1]=1;if (k!=1)    while (l<=100) {        a[++a[0]]=l;        l*=k;    }    int flag=0;    for (f=1;f<=a[0];f++) {    if (n-a[f]>=0)    if (!getsg(n-a[f])) {        printf("%d %d   %d\n",n,k,a[f]);        flag=1;        break;        }    }    if (!flag) printf("%d %d   %d\n",n,k,0);}}return 0;}

AC程序:

#include <cstdio>#include <iostream>#include <vector>#include <string.h>using namespace std;int main() {int t;scanf("%d",&t);while (t--) {int n,k,i,ans;scanf("%d%d",&n,&k);if (k>n) ans=0; else {if (k%2) {if (n%2) ans=1; else ans=0;} else {if ((n+1)%(k+1)==0) ans=k; else     if (((n+1)%(k+1))%2) ans=0; else ans=1;}}printf("%d\n",ans);}return 0;}