P10975 Mondriaan's Dream / 蒙德里安的梦想 题解

· · 题解

P10975 Mondriaan's Dream / 蒙德里安的梦想 题解

思路

惊喜地发现 Kasteleyn 公式的时空复杂度均是最优的。理论上是本题的最优解法。

Kasteleyn 公式

对于 m×n 的矩形网格,用 2×1 多米诺骨牌完美覆盖的方案数 \mathcal{M}(m,n) 由以下公式给出:

\mathcal{M}(m,n) = \prod_{j=1}^m \prod_{k=1}^n \left(4\cos^2\frac{\pi j}{m+1} + 4\cos^2\frac{\pi k}{n+1}\right)^{\frac{1}{4}}

简单地代入本题即可,注意精度。

参考代码

#include <bits/stdc++.h>
using namespace std;
typedef long double ld;
void solve() {
    int h,w;
    while(cin>>h>>w&&(h||w)){
        // 若面积为奇数,显然无法用2x1矩形填满
        if((h*w)%2){
            cout<<0<<endl;
            continue;
        }
        ld res=1.0;
        ld pi=acos(-1.0);
        for(int j=1;j<=h;j++){
            for(int k=1;k<=w;k++){
                ld t1=4*pow(cos(pi*j/(h+1)),2);
                ld t2=4*pow(cos(pi*k/(w+1)),2);
                res*=pow(t1+t2,0.25);
            }
        }
        cout<<(long long)round(res)<<endl;
    }
}

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    solve();
    return 0;
}

惭愧地发现竟然没有 dp 快(或许是 O2 的缘故?),做了些许优化,使得速度、空间和 dp 相同了。

优化后的代码:

#include<bits/stdc++.h>
using namespace std;
typedef __float128 f128;
typedef long long ll;
ll ans[12][12];
f128 cs[12][12];
void pre(){
    memset(ans,0,sizeof(ans));
    f128 pi=acosl(-1.0);
    //预处理cos项
    for(int n=1;n<=11;n++)
        for(int i=1;i<=n;i++){
            f128 c=cosl(pi*i/(f128)(n+1));
            cs[n][i]=4.0*c*c;
        }
    for(int h=1;h<=11;h++){
        for(int w=1;w<=11;w++){
            if((h*w)%2||ans[h][w])continue;
            int n=h,m=w;
            if(n%2)swap(n,m);//保证n为偶数
            f128 res=1.0;
            for(int i=1;i<=n/2;i++)
                for(int j=1;j<=m;j++)
                    res*=sqrtl((long double)(cs[n][i]+cs[m][j]));

            ans[h][w]=ans[w][h]=(ll)(res+0.5);
        }
    }
}

int main(){
    ios::sync_with_stdio(0);cin.tie(0);
    pre();
    int h,w;
    while(cin>>h>>w&&(h||w))cout<<ans[h][w]<<"\n";
    return 0;
}

参考资料

  1. 关于 Kasteleyn 公式的详细介绍

  2. 详细证明过程下载链接(PDF in English)

结语

Perhaps, beyond conventional methods, there lie countless unconventional ones. They may be bizarre or hard to code, yet they form this digital empire—created by humanity.

upd. 2026.06.13 实则比 dp 快,我原来误把打表的当成 dp 的了