P10501 Cutting Game 题解

· · 题解

直接 SG 函数,不会的可以看 OI Wiki。

设 SG_{w,h} 表示在 w\times h 的矩形纸张中先手的 SG 值,很显然 SG_{1,1}=0(因为对方搞出了 1\times 1 纸张)。如果 w 和 h 中只有一个 1,那搞成 1\times 1 就赢了。因此当 w,h>1 时绝对不能把纸张搞成 1\times h 或 w\times 1。

于是有

SG_{w,h}=\begin{cases} 0 & w=1,h=1 \\ \operatorname{mex}(\{x|x=SG_{i,h}\oplus SG_{w-i,h}\bigvee x=SG_{w,j}\oplus SG_{w,h-j}\}) & w>1\vee h>1 \end{cases}

其中 i\in(1,w-1),j\in(1,h-1)。

代码 ↓

#include <iostream>
#include <tuple>
#include <map>
using namespace std;
int dp[201][201];
int sg(const int w,const int h) {
    if(dp[w][h]>=0) return dp[w][h];
    if(w==1&&h==1) return dp[w][h]=0;
    map<int,bool> mp;
    for(int i=2;i<w-1;i++)
        mp[sg(i,h)^sg(w-i,h)]=1;
    for(int i=2;i<h-1;i++)
        mp[sg(w,i)^sg(w,h-i)]=1;
    for(dp[w][h]=0;;dp[w][h]++)
        if(!mp[dp[w][h]]) return dp[w][h];
}
int main() {
    cin.tie(nullptr)->sync_with_stdio(false);
    for(auto &i: dp)
        for(auto &j: i)
            j=-1;
    for(int w,h;cin>>w;) {
        cin>>h;
        cout<<(sg(w,h)?"WIN\n":"LOSE\n");
    }
    return 0;
}

禁止抄代码!!!