P10975 Mondriaan’s Dream / 蒙德里安的梦想 题解
思路
- 首先考虑暴力搜索,但显然时间复杂度会指数级爆炸,会 TLE。
- 考虑状压 DP,核心思路:只考虑横着放的骨牌,剩下的空位竖着放自动填满。用二进制表示每一列的填充状态,DP 转移合法状态。可以通过此题,代码略。
立刻联想到 Kasteleyn 公式,它是物理学家 P. W. Kasteleyn 在 1961 年给出的,专门用来计算 m×n 矩形网格用 2×1 多米诺骨牌完美覆盖的方案数。
时空复杂度对比
| 方法 | 时间复杂度 | 空间复杂度 |
|---|---|---|
| Kasteleyn 公式 | ||
| 状压 DP | ||
| 暴力搜索 DFS |
惊喜地发现 Kasteleyn 公式的时空复杂度均是最优的。理论上是本题的最优解法。
Kasteleyn 公式
对于 m×n 的矩形网格,用 2×1 多米诺骨牌完美覆盖的方案数 由以下公式给出:
简单地代入本题即可,注意精度。
参考代码
#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;
}参考资料
结语
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.