Color UVALive - 7040 (容斥+组合数)

Recently, Mr. Big recieved n owers from his fans. He wants to recolor those owers with m colors. The
owers are put in a line. It is not allowed to color any adjacent owers with the same color. Flowers i and
i + 1 are said to be adjacent for every i, 1 ≤ i < n. Mr. Big also wants the total number of different
colors of the n owers being exactly k.
Two ways are considered different if and only if there is at least one ower being colored with different
colors.
Input
The first line of the input gives the number of test cases, T. T test cases follow. T is about 300 and in
most cases k is relatively small.
For each test case, there will be one line, which contains three integers n, m, k (1 ≤ n, m ≤ 109
,
1 ≤ k ≤ 106
, k ≤ n, m).
Output
For each test case, output one line containing ‘Case #x: y’, where x is the test case number (starting
from 1) and y is the number of ways of different coloring methods modulo 109 + 7.
Sample Input
2
3 2 2
3 2 1
Sample Output
Case #1: 2
Case #2: 0

|A1¯¯¯¯A2¯¯¯¯...Ak¯¯¯¯|

=k(k1)n1|Ai|+|AiAj|+...+(1)k|A1A2...Ak|

|Ai|=C1k(k1)(k2)n1

|Ai1Ai2...Aij|=Cjk(kj)(kj1)n1

ans=|A1¯¯¯¯A2¯¯¯¯...Ak¯¯¯¯|Ckm

#include
#include
#include
#include
#include
#define N 1000005
#define INF 10000000000
#define mod 1000000007
using namespace std;
typedef long long  ll;
ll fac[N],inv[N];
int n,m,k;
ll P(ll a,ll b)
{
    ll ans=1;
    while(b)
    {
        if(b&1)
            ans=ans*a%mod;
        a=a*a%mod;
        b>>=1;
    }
    return ans;
}
ll getCom(int n,int m)
{
    return fac[n]*inv[m]%mod*inv[n-m]%mod;
}
ll A(int x)
{
    return (k-x)*P(k-x-1,n-1)%mod;
}
ll inv2[N];
void init()
{
    fac[0]=1;
    for(int i=1;i1]*i%mod;
    inv[1000000]=P(fac[1000000],mod-2);
    for(int i=1000000;i>0;i--)
        inv[i-1]=inv[i]*i%mod;
    inv2[1]=1;
    for(int i=2;i1到n对mod取模的逆元
        inv2[i]=(mod-mod/i)*inv2[mod%i]%mod;
}
int main()
{
    int t;
    init();
    scanf("%d",&t);
    int cal=1;
    while(t--)
    {
        scanf("%d%d%d",&n,&m,&k);
        printf("Case #%d: ",cal++);
        if(k==1)
        {
            if(n==1)
                printf("%d\n",m);
            else
                printf("0\n");
            continue;
        }
        ll ans=A(0);
        //cout<for(int i=1;iif(i&1)
                ans=(ans-getCom(k,i)*A(i)%mod+mod)%mod;
            else
                ans=(ans+getCom(k,i)*A(i)%mod)%mod;
        }
        ans=ans*m%mod;
        for(int i=2;i<=k;i++)
            ans=ans*(m-i+1)%mod*inv2[i]%mod;
        printf("%lld\n",ans);
    }
    return 0;
}

你可能感兴趣的:(组合数,容斥原理)