zoukankan      html  css  js  c++  java
  • HDU 6114 Chess【逆元+组合数】(组合数模板题)

    <题目链接>

    题目大意:

    車是中国象棋中的一种棋子,它能攻击同一行或同一列中没有其他棋子阻隔的棋子。一天,小度在棋盘上摆起了许多車……他想知道,在一共N×M个点的矩形棋盘中摆最多个数的車使其互不攻击的方案数。他经过思考,得出了答案。但他仍不满足,想增加一个条件:对于任何一个車A,如果有其他一个車B在它的上方(車B行号小于車A),那么車A必须在車B的右边(車A列号大于車B)。 
    现在要问问你,满足要求的方案数是多少。

    Input

    第一行一个正整数T,表示数据组数。 
    对于每组数据:一行,两个正整数N和M(N<=1000,M<=1000)。Output对于每组数据输出一行,代表方案数模1000000007(1e9+7)。

    Sample Input

    1

    1 1

    Sample Output

    1

    解题分析:

    其实仔细推敲这题之后,不难发现,由于n和m不一定想等,所以在棋盘中放置最多个数的车,并使其不攻击,即求 C(max(n,m),min(n,m))。因为,假设n>m,即行数大于列数,此时要使棋盘中车尽可能的多,只能每一列都放一个车,而这m个车摆放的不同方案数即为在 n行中挑选出 m行来放这 m个车。所以,此题就很自然的转化为了组合数的求解。

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<string>
    #include<algorithm>
    #define ll long long
     
    using namespace std;
     
    const int mod = 1000000007;
     
    ll fast_pow(ll x, ll n)
    {
        ll ans = 1;
        while (n)
        {
            if (n & 1) ans = (ans*x) % mod;
            x = (x*x) % mod;
            n >>= 1;
        }
        return ans;
    }
     
    ll inv(ll a, ll p)    //费马定理求a关于p的逆元
    {
        return fast_pow(a, p - 2);
    }
     
    ll C(ll n, ll m)    //求n中挑选m个的方案数
    {
        ll ans = 1;
        for (ll i = n - m + 1; i <= n; i++) ans = (ans*i) % mod;
        for (ll i = 1; i <= m; i++) ans = (ans*inv(i, mod)) % mod;
        return ans;
    }
     
    int main()
    {
        int t;
        scanf("%d", &t);
        while (t--)
        {
            ll n, m;
            scanf("%lld%lld", &n, &m);
            printf("%lld
    ", C(max(n, m), min(n, m)));
        }
        return 0;
    } 

    2018-08-12

  • 相关阅读:
    odoo 错误 Resource interpreted as Stylesheet but transferred with MIME type application/x-css:
    Android架构师之路-架构到代码的演练
    Android架构师之路-架构师的决策
    EventBus
    Android架构师之路-UML图形思考
    Android架构师之路-oop
    EventBus
    java定义接口监听器详解
    INSTALL_FAILED_NO_MATCHING_ABIS
    android---NDK开发helloworld(jni)
  • 原文地址:https://www.cnblogs.com/00isok/p/9465478.html
Copyright © 2011-2022 走看看