hdu 1536 && hdu 1944 S-Nim (Nim Game)

The first line gives the set of feasible operations of size k, and then the k numbers represent the number of stones that can be taken in a pile at one time. Whoever finishes first wins.

A number m in the second line indicates that m games will be played.

The following m lines, the first number n in each line represents the number of piles of stones, and the number of n piles of stones after. Every time the first player wins, output W, otherwise output L. All games played for each sample are output on one line.

Find SG function template

recursion

//N is the maximum number of stones in a pile
//M is the maximum number of operable sets
//x is how many stones are in the actual pile
//k is the size of the actual operable set s
//Note: sg needs to be initialized to -1, each set needs to be initialized once, and s needs to be initialized and sorted from small to large
int s[N], sg[N], k;  
int getsg(int x) {
	int i;  
    if(sg[x]!=-1) return sg[x];  
    bool vis[M];  
    memset(vis,0,sizeof(vis));  
    for(i=0; i < k && x>=s[i]; i++) vis[getsg(x-s[i])]=1;
    for(i=0; ; i++)	{
    	if(!vis[i]) {  
            sg[x]=i;  
            break;  
        }
    }
    return sg[x];  
}

By meter

//N is the maximum number of stones in a pile
//M is the maximum number of operable sets
//n indicates how much table to play
//k is the size of the actual operable set s
//Note: s needs to be initialized and sorted from small to large
bool mex[M];
int sg[N], s[M], k;
void getsg(int n) {
    memset(sg, 0, sizeof sg);
    int i, j;
    for(i = 0; i <= n; i++) {
        memset(mex, 0, sizeof mex);
        for(j = 0; j < k && i >= s[j]; j++) {
            mex[sg[i - s[j]]] = 1;
        }
        for(j = 0; ; j++) {
            if(mex[j] == 0) {
                sg[i] = j;
                break;
            }
        }
    }
}

#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
#define N 110//Maximum number of operable collections
#define M 10010//Maximum number of stones in a pile
int s[110];//sort from small to large
int sg[10010];//
bool mes[10010];


void get_sg(int n){//n represents the actual operable set size
	
	memset(sg,0,sizeof(sg));
	for(int i=0;i<10001;i++){
		memset(mes,0,sizeof(mes));
		for(int j=0;j<n&&s[j]<=i;j++){
			mes[sg[i-s[j]]]=1;
		}
		for(int j=0;j<10001;j++){
			if(mes[j]==0){
				sg[i]=j;
				break;
			}
		}
	}
	
}

int main(){
	int k;
	while(scanf("%d",&k)&&k){
		
		for(int i=0;i<k;i++)
		scanf("%d",&s[i]);
		
		sort(s,s+k);
		get_sg(k);
		int m;
		scanf("%d",&m);
		while(m--){
			
			int num;
			scanf("%d",&num);
			
			int tmp=0;
			for(int i=0;i<num;i++){
				int x;
				scanf("%d",&x);
				tmp^=sg[x];
			}
			if(tmp)
			printf("W");
			else printf("L");
		}
		printf("\n");
	}
	return 0;
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325778035&siteId=291194637