【codechef】Superlucky Numbers(组合取模,枚举)

Eshaan and Nischay decided to play a game. Nischay asked Eshaan to choose 2 distinct digits A and B. Eshaan calls a positive integer “lucky”, if it contains only the digits A and B. Nischay calls this number “superlucky” if sum of its digits is “lucky”.

For Example : If Eshaan chooses A = 1 and B = 3, then number 12 isn’t lucky but 133 or 1133131 are lucky. Also number 1133131 is superlucky but 133 is not.

Now Eshaan wants Nischay to find how many superlucky numbers of length exactly N are there.

Help Nischay to find the answer to this problem.

Since the answer can be very large, print answer modulo (109+7).

 

Input

  • The first line of input contains T, denoting the number of test cases.
  • The second line of input contains 3 integers A,B and N.

 

Output

  • Print a single integer — the answer to the problem modulo (109 +7).

Constraints

  • 1 ≤ T ≤ 50
  • 1 ≤ A < B ≤ 9
  • 1 ≤ N ≤ 106

 

Example

Input:
2
1 3 3
2 3 10

Output:
1
165

 

Explanation

Example case 1. Only one number of length 3 is superlucky which is 111 because 111 is lucky and sum of its digits 1+1+1=3 is also lucky.

http://www.codechef.com/problems/CLCO02

只由a和b组成且各个位上的和是lucky数且必须是n位的数字有几个?

#include<bits/stdc++.h>
using namespace std;
int a,b,n;
long long MOD=1e9+7;
long long fact[1000006]={0};
long long ifact[1000006]={0};

long long mulmod(long long a,long long b) //pow函数
 {	long long x=1,y=a;
 	while(b>0)
 	 {
 	 	if(b&1)
 	 	  x=(x*y)%MOD;
 	 	y=(y*y)%MOD;
 	 	b=b>>1;
 	 }
 	return x;
 }
 
bool isLucky(int m){
	while(m)
	 {
	 	if(m%10==a || m%10==b) // 这个数的某一位是a或b
	 	  m/=10;
	 	else 
	 	  return false;
	 }
	return true;
}

int main(){
	fact[0]=ifact[0]=1;
	for(int i=1;i<=1000000;i++)
	  fact[i]=(i*fact[i-1])%MOD;
	for(int i=1;i<=1000000;i++)
	  ifact[i]=mulmod(fact[i],MOD-2);
	
	int t;
	cin>>t;
	while(t--)
	 {
	 	cin>>a>>b>>n;
	 	int c=0;
	 	for(int i=0;i<=n;i++) //枚举这个数里面a出现的个数
	 	 {
	 	 	int m=i*a+b*(n-i); //各位上数字的和
	 	 	if(isLucky(m))   //判断这个和是否是lucky数
	 	 	  {
	 	 	  	long long ans=fact[n];
	 	 	  	long long den=(ifact[i]*ifact[n-i])%MOD; //组合模板,这些a摆放的方法数
	 	 	  	ans=(ans*den)%MOD;
	 	 	  	c=(c+ans)%MOD;
	 	 	  }
	 	 }
	 	 cout<<c<<endl;
	 }
}
下面是我总结的组合取模模板:

long long MOD=1e9+7;
long long fact[1000006];
long long ifact[1000006];
main(){
	fact[0]=ifact[0]=1;
	for(int i=1;i<=1000000;i++)
	  fact[i]=(i*fact[i-1])%MOD;
	for(int i=1;i<=1000000;i++)
	  ifact[i]=mulmod(fact[i],MOD-2);

	 int n,m;
	 cin>>n>>m;
	 long long ans=fact[n];
	 long long den=(ifact[m]*ifact[n-m])%MOD;
	 ans=(ans*den)%MOD;
	 cout<<ans<<endl;



你可能感兴趣的:(【codechef】Superlucky Numbers(组合取模,枚举))