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
第一道二项式反演。。
k*(k-1)^(n-1) 代表我最多选k个的相邻颜色不同的方案数
很好求
我们求的是恰好使用k个的方案数 记为f【i]
二项式反演就完了。
用到了 组合数的线性的递推,逆元
1 2 #include <bits/stdc++.h> 3 using namespace std; 4 typedef long long ll; 5 const int N = 2000000; 6 #define int ll 7 const int mod = 1e9+7; 8 int cm[N]; 9 int ck[N]; 10 int fac[N]; 11 int inv[N]; 12 int n,m,k; 13 14 int ksm(int a,int b,int p) 15 { 16 int ans = 1; a%=p; 17 for(;b;b>>=1,a*=a,a%=p)if(b&1)ans *= a,ans %= p; 18 return ans ; 19 } 20 void Pre() 21 { 22 fac[0]=1; 23 for(int i=1;i<=k;i++) 24 fac[i]=fac[i-1]*i%mod,inv[i]=ksm(i,mod-2,mod); 25 ; 26 // for(int i=1;i<=k;i++)cout<<fac[i]<<" "<<inv[i]<<endl; 27 cm[0]=ck[0]=1; 28 for(int i=1;i<=k;i++)cm[i]=cm[i-1]*(m-i+1)%mod*inv[i]%mod; 29 for(int i=1;i<=k;i++)ck[i]=ck[i-1]*(k-i+1)%mod*inv[i]%mod; 30 31 //for(int i=1;i<=k;i++)cout<<cm[i]<<endl; 32 } 33 34 signed main() 35 { 36 37 // freopen("datte.txt","r",stdin); 38 //freopen("my.out","w",stdout); 39 int T;cin>>T; 40 41 int cas=0; 42 while(T--) 43 { 44 cin>>n>>m>>k; 45 Pre(); 46 int ans = cm[k]; 47 // cout<<ans<<endl; 48 int t=0; 49 for(int i=0;i<=k;i++) 50 { 51 int f=1; 52 if((k-i)%2==1)f=-1; 53 t += f*ck[i]%mod*i%mod*ksm(i-1,n-1,mod)%mod; 54 t %= mod; 55 t+=mod; 56 t%=mod; // 注意可能是负的, 57 // cout<<i<<" "<<t<<endl; 58 59 } 60 // cout<<ans<<" " <<t<<endl; 61 printf("Case #%d: %lld\n",++cas,ans*t%mod); 62 63 } 64 65 /* 66 67 10 68 1000000000 1000000000 1000000 69 100000000 100000000 1000000 70 */ 71 }
标签:Color,number,owers,反演,int,UVALive,ans,test,line 来源: https://www.cnblogs.com/zhangbuang/p/10989289.html