跳到正文

题解

CF293B Distinct Paths 题解

WOL_GO约 4 分钟
原文
文章信息与版本

文章信息

发布
2023年7月19日
收录
2026年8月25日
更新
2026年11月8日
篇幅
约 4 分钟
题目
CF293B

版本

  1. v1当前

题目传送门

真服了 CF 的 RemoteJudge 评测,交了好几发都是 UKE,有相同情况的同学可以交到原题评测。

  • 可以发现,当 n+m−1>kn+m-1>k 时,显然无解,且经过的颜色肯定超过了两种及其以上的颜色。

  • 合法的 nn,mm 范围比较小,可以使用搜索。

  • 使用状压的方式记录当前使用的颜色,fx,y\mathit{f}_{x,y} 表示搜索到 (x,y)(x,y) 使用的颜色集合。

  • 剪枝优化:

  1. 可行性剪枝:当剩下的步数大于可用的颜色数时,可以直接结束搜索。

  2. 排除等效冗余:如果当前有 kk 种颜色还使用,对于空白格子染任何一种染色的贡献都是相同的,只需要选择一种颜色计算,其他颜色累加即可。

代码

C++
#include<bits/stdc++.h>
using namespace std;
const int maxn=1e6+5;
void read(int &xx){
    register char ch=getchar();
    register int ans=0;
    char t=0;
    while(!isdigit(ch))t|=ch=='-',ch=getchar/*_unlocked*/();
    while(isdigit(ch))ans=(ans<<3)+(ans<<1)+(ch^48),ch=getchar/*_unlocked*/();
    xx=t?-ans:ans;
    return ;
}
void write(int x){
    if(x<0){
        putchar('-');
        x*=-1;
    }
    char wr[18];
    int cnt=1;
    if(x==0){
        putchar('0');
        putchar('\n');
        return ;
    }
    while(x){
        wr[cnt++]=x%10+'0';
        x/=10;
    }
    for(cnt--;cnt;cnt--){
        putchar(wr[cnt]);
    }
    putchar('\n');
    return;
}
const int dx[2]={1,0},dy[2]={0,1},mod=1e9+7;
int a[1005][1005];
long long f[1005][1005];
int ans[1005][1005];
int n,m,k;
bool use[maxn];
int dfs(int x,int y){//1<<(i-1)
    if(y>m){
        x++,y=1;
    }
    if(x>n)return 1;
    int s=f[x-1][y]|f[x][y-1];
    int sum=0;
    int left=0;
    for(int i=1;i<=k;i++){
        if(!(s&(1<<(i-1))))left++;
    }
    if(n+m-x-y+1>left) return 0;
    int now=-1;
    for(int i=1;i<=k;i++){
        if((a[x][y]&&a[x][y]!=i)||((s>>(i-1))&1))continue;
        f[x][y]=s|1<<(i-1);
        if(!use[i]){
            use[i]=1;
            if(now==-1){
                now=dfs(x,y+1);
            }
            sum+=now;
            sum%=mod;
            use[i]=0;
        }
        else sum+=((dfs(x,y+1))%mod),sum%=mod;
    }
    // cout<<sum<<"\n";
    return sum;
}
int main(){
    read(n);
    read(m);
    read(k);
    for(int i=1;i<=n;i++)for(int j=1;j<=m;j++)read(a[i][j]),use[a[i][j]]=1;
    if(n+m-1>k){
        puts("0");
        return 0;
    }
    write(dfs(1,1)%mod);
    return 0;
}
原文
存档评论2 条抓取于