容斥(第一题)

6451: Iroha and a Grid

时间限制: 1 Sec   内存限制: 128 MB
提交: 218   解决: 62
[ 提交][ 状态][ 讨论版][命题人: admin]

题目描述

We have a large square grid with H rows and W columns. Iroha is now standing in the top-left cell. She will repeat going right or down to the adjacent cell, until she reaches the bottom-right cell.
However, she cannot enter the cells in the intersection of the bottom A rows and the leftmost B columns. (That is, there are A×B forbidden cells.) There is no restriction on entering the other cells.
Find the number of ways she can travel to the bottom-right cell.
Since this number can be extremely large, print the number modulo 109+7.

Constraints
1≤H,W≤100,000
1≤A<H
1≤B<W

输入

The input is given from Standard Input in the following format:

H W A B

输出

Print the number of ways she can travel to the bottom-right cell, modulo 109+7.

样例输入

2 3 1 1

样例输出

2

提示

We have a 2×3 grid, but entering the bottom-left cell is forbidden. The number of ways to travel is two: "Right, Right, Down" and "Right, Down, Right".

计算从矩形左上角到右下角并减掉左下角矩形的总次数

从左上角到右下角总次数为组合数 C(n+m,n)或C(n+m,m)

利用逆元计算组合数

然后用容斥的思想,正难则反易,用总次数减去不能走的就是所求的

代码:

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const ll MOD=1e9+7;
const ll INF=1e6+10;
ll f[INF],re[INF];
ll pow_mod(ll a,ll b){
    ll ret=1;
    while(b){
        if(b&1) ret=(ret*a)%MOD;
        a=(a*a)%MOD;
        b >>= 1;
    }
    return ret;
}
void init(){
    f[0]=1;
    re[0]=1;
    for(int i=1; i<INF; i++){
        f[i]=(i*f[i-1])%MOD;
        re[i]=pow_mod(f[i],MOD-2);
    }
}
ll ways(int n,int m){
    return (f[n]*re[m])%MOD*re[n-m]%MOD;
}
int main()
{
    init();
    int h,w,a,b;
    cin>>h>>w>>a>>b;
    long long ans=0,sum=0;
    for(int i=w; i>=b+1; i--){
        sum=ways(h-a+i-2,h-a-1)%MOD*ways(w+a-i-1,w-i)%MOD;
        ans=(ans+sum)%MOD;
    }
    cout<<ans%MOD<<endl;
    return 0;
}


猜你喜欢

转载自blog.csdn.net/renzijing/article/details/80386589
今日推荐