0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

paizaレベルアップ問題集「Sランクレベルアップメニュー」をやってみた~Grundy数

0
Last updated at Posted at 2026-12-01

paizaレベルアップ問題集「Sランクレベルアップメニュー」の「Grundy数」をやってみました。


問題


方針

あくまで後問の「タイルゲーム」のためのGrundy数です。一般的なニムゲームにおけるGrundy数とは異なります。

$\text{grundy}(x)=\text{mex}(\{\text{grundy}(i)\oplus\text{grundy}(x-i-2)|i=0,1,2,\dots,x-2\})$
を再帰的に計算します。但し、同じ$x$に対してGrundy数を何回も計算することになりますので、メモ化再帰を使用します。


mex関数(引数:非負整数の集合$S$)

  • $y=0$で初期化します
  • 以下、繰り返し
    • $y\notin S$の場合、ループ脱出
    • $y$をインクリメントします
  • $y$を返します

grundy関数($x\ge 2$について)

  • $\text{grundy}(x)$が計算済みの場合、その値を返します
  • $\text{grundy}(x)$が未計算の場合
    • 非負整数集合$S$を空集合$\emptyset$で初期化する
    • $i=0,1,2,\dots,x-2$に対して
      • $S=S\cup\{\text{grundy}(i)\oplus\text{grundy}(x-i-2)\}$で更新します
    • $\text{grundy}(x)=\text{mex}(S)$を記録し、その値を返します

実装例
#include <iostream>
#include <unordered_set>
#include <unordered_map>
using namespace std;

unsigned mex(const unordered_set<unsigned> &S) {
	unsigned u = 0;
	while (S.count(u)) {
		u++;
	}
	return u;
}

unsigned _grundy(unsigned x, unordered_map<unsigned, unsigned> &M) {
	if (M.count(x)) {
		return M[x];
	}
	if (x == 0 || x == 1) {
		return M[x] = 0;
	}
	unordered_set<unsigned> S;
	for (unsigned i = 0; i <= x - 2; i++) {
		S.insert(_grundy(i, M) ^ _grundy(x - i - 2, M));
	}
	return M[x] = mex(S);
}

unsigned grundy(unsigned n) {
	unordered_map<unsigned, unsigned> M;
	return _grundy(n, M);
}

int main(void) {
	unsigned n;
	cin >> n;
	cout << grundy(n) << endl;
	return 0;
}

C言語では、mex関数にstrlen関数を使うという裏技があります。

#include <stdio.h>
#include <string.h>

unsigned _grundy(unsigned x, unsigned *G) {
	if (~G[x]) {
		return G[x];
	}
	if (x == 0 || x == 1) {
		return G[x] = 0;
	}
	char S[x + 1];
	memset(S, 0, sizeof(S));
	for (unsigned i = 0; i <= x - 2; i++) {
		unsigned g = _grundy(i, G) ^ _grundy(x - i - 2, G);
		S[g] = 1;
	}
	return G[x] = strlen(S);
}

unsigned grundy(unsigned n) {
	unsigned G[n + 1];
	memset(G, 0xFF, sizeof(G));
	return _grundy(n, G);
}

int main(void) {
	unsigned n;
	scanf("%u", &n);
	printf("%u\n", grundy(n));
	return 0;
}
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?