题解:P17388 [PacNW 2025] Server Room

· · 题解

首先考虑 n\times m\leq 400。一眼翻转。小的那个不超过 20。于是考虑状压。

令 f_{i,j} 表示前 i 行,第 i 行状态为 j 的最大值,g_{i,j} 表示在此情况下的方案数。转移是显然的。

考虑直接做复杂度是 \mathcal O(\max(n,m)4^{\min(n,m)}),这玩意显然过不了。

考虑优化。预处理每一个自己行内部没有相邻点的状态。打表发现这样的状态不超过 20000 个。但是这样还是有点难以通过。

考虑再加一个优化。我们可以预处理一个状态所对应的可以转移的相邻状态。打表发现这个的总和是不超过 6\times 10^7 的。再乘 20 就可过了。也跑不满。

#include<bits/stdc++.h>
using namespace std;
/*

*/
struct FSI{
    template<typename T>
    FSI& operator >> (T &res){
        res=0;T f=1;char ch=getchar();
        while (!isdigit(ch)){if (ch=='-') f=-1;ch=getchar();}
        while (isdigit(ch)){res=res*10+ch-'0';ch=getchar();}
        res*=f;
        return *this;
    }
}scan;
const int N=410,mod=998244353,M=20,K=20010;
int n,m,i,j,k,tx,ty,ans,sum;
char a[N][N],t[N][N];
int cnt,c[1<<M],st[1<<M],p[N],num;
int f[N][K],g[N][K];
int fx[5]={0,0,1,0,-1};
int fy[5]={0,1,0,-1,0};
vector<int> G[K];
void flip()
{
    int i,j;
    for (i=0;i<n;i++)
    {
        for (j=0;j<m;j++) t[j][n-i-1]=a[i][j];
    }
    swap(n,m);
    for (i=0;i<n;i++)
    {
        for (j=0;j<m;j++) a[i][j]=t[i][j];
    }
}
int main()
{
    scan>>n>>m;
    for (i=0;i<n;i++) scanf("%s",a[i]);
    for (i=0;i<n;i++)
    {
        for (j=0;j<m;j++)
        {
            if (a[i][j]=='2')
            {
                a[i][j]='0';
                for (k=1;k<=4;k++)
                {
                    tx=i+fx[k];
                    ty=j+fy[k];
                    if (tx>=0&&tx<n&&ty>=0&&ty<m) a[tx][ty]='0';
                }
            }
        }
    }
    if (n<m) flip();
    for (i=0;i<n;i++)
    {
        num=0;
        for (j=0;j<m;j++) num+=(1<<j)*(a[i][j]-'0');
        p[i]=num;
    }
    for (i=0;i<(1<<m);i++) c[i]=__builtin_popcount(i);
    for (i=0;i<(1<<m);i++)
    {
        if (!((i<<1)&i)) st[++cnt]=i;
    }
    for (i=1;i<=cnt;i++)
    {
        for (j=1;j<=cnt;j++)
        {
            if (!(st[i]&st[j])) G[i].push_back(j);
        }
    }
    for (i=1;i<=cnt;i++)
    {
        if ((st[i]|p[0])==p[0]) f[0][i]=c[st[i]],g[0][i]=1;
    }
    for (i=1;i<n;i++)
    {
        for (j=1;j<=cnt;j++)
        {
            if ((st[j]|p[i])!=p[i]) continue;
            for (auto k:G[j])
            {
                if ((st[k]|p[i-1])!=p[i-1]) continue;
                if (f[i-1][k]+c[st[j]]>f[i][j]) f[i][j]=f[i-1][k]+c[st[j]],g[i][j]=g[i-1][k];
                else if (f[i-1][k]+c[st[j]]==f[i][j]) g[i][j]=(g[i][j]+g[i-1][k])%mod;
            }
        }
    }
    for (i=1;i<=cnt;i++)
    {
        if (f[n-1][i]>ans) ans=f[n-1][i],sum=g[n-1][i];
        else if (f[n-1][i]==ans) sum=(sum+g[n-1][i])%mod;
    }
    printf("%d %d\n",ans,sum);
    return 0;
}