跳到正文

题解

题解:P17700 [ICPC 2019 Nanjing R] Chessboard

ocean_ZGY约 2 分钟
原文
文章信息与版本

文章信息

发布
2026年10月16日
收录
2026年10月21日
更新
2026年10月22日
篇幅
约 2 分钟
获赞
4
题目
P17700

版本

  1. v1当前

题目传送门

解题思路

观察题目条件,很容易发现每一种合法的粉刷方案一定是从一个角开始,每次向外扩展一整行或者一整列。铺满整个棋盘一共需要拓展 (n−1)+(m−1)(n - 1) + (m - 1) 次。

从单个角出发的方案数为组合数 (n+m−2n−1)\binom{n + m - 2}{n - 1}。矩形一共有四个角,所以答案为 4×(n+m−2n−1)4 \times \binom{n + m - 2}{n - 1}。

由于这里需要求组合数取模,所以需要预处理阶乘、线性逆元、阶乘逆元,用模意义下组合数公式计算即可。

当 n=1n = 1 或者 m=1m = 1 时,四个角重复计数,实际上只有两个角,所以答案是 22。

代码实现

C++
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int mod=1e9+7;
int t,fac[2000010],inv[2000010],invfac[2000010];
signed main(){
    cin>>t;
    fac[0]=1;
    for(int i=1;i<=2000000;i++){ //正常阶乘
        fac[i]=(fac[i-1]*i)%mod;
    }
    inv[1]=1;
    for(int i=2;i<=2000000;i++){ //逆元
        inv[i]=(mod-mod/i)*inv[mod%i]%mod;
    }
    invfac[0]=1;
    for(int i=1;i<=2000000;i++){ //阶乘逆元
        invfac[i]=(invfac[i-1]*inv[i])%mod;
    }
    while(t--){
        int n,m;
        cin>>n>>m;
        if(n==1||m==1){ //特判
            cout<<2<<endl;
        }else{
            cout<<(4*((((fac[n+m-2]*invfac[n-1])%mod)*invfac[m-1])%mod))%mod<<endl;
        }
    }
    return 0;
}
原文