Description
给一个数字串s和正整数d, 统计s有多少种不同的排列能被d整除(可以有前导0)。例如123434有90种排列能
被2整除,其中末位为2的有30种,末位为4的有60种。
Input
输入第一行是一个整数T,表示测试数据的个数,以下每行一组s和d,中间用空格隔开。s保证只包含数字0, 1
, 2, 3, 4, 5, 6, 7, 8, 9.
Output
每个数据仅一行,表示能被d整除的排列的个数。
Sample Input
7
000 1
001 1
1234567890 1
123434 2
1234 7
12345 17
12345678 29
000 1
001 1
1234567890 1
123434 2
1234 7
12345 17
12345678 29
Sample Output
1
3
3628800
90
3
6
1398
3
3628800
90
3
6
1398
HINT
在前三个例子中,排列分别有1, 3, 3628800种,它们都是1的倍数。
【限制】
100%的数据满足:s的长度不超过10, 1<=d<=1000, 1<=T<=15
状压DP。。。
1 #include<iostream> 2 #include<cstdio> 3 #include<cmath> 4 #include<algorithm> 5 #include<cstring> 6 #include<vector> 7 #include<map> 8 #include<set> 9 #include<queue> 10 #define maxn 100010 11 #define ll long long 12 #define inf 600000000 13 using namespace std; 14 int num[15],f[1<<15][1010],a[15],tot[15]; 15 int main(){ 16 for(int i=1;i<=15;i++)num[i]=1<<(i-1); 17 int n; 18 scanf("%d",&n); 19 for(int i=1;i<=n;i++){ 20 int x;char ch[15];scanf("%s %d",ch,&x); 21 int len=strlen(ch),sum=1; 22 for(int t=0;t<=15;t++)a[t]=0,tot[t]=0; 23 for(int j=0;j<=len-1;j++)a[j+1]=ch[j]-48,tot[ch[j]-48]++; 24 memset(f,0,sizeof(f)); 25 f[0][0]=1; 26 for(int t=0;t<=(1<<(len));t++) 27 for(int j=0;j<=x;j++) 28 for(int k=1;k<=len;k++) 29 if((t&num[k])==0){ 30 f[t|num[k]][(a[k]+j*10)%x]+=f[t][j]; 31 } 32 for(int j=0;j<15;j++) 33 for(int k=1;k<=tot[j];k++) 34 sum*=k;//把重复的数用1~n编号,有n!种可能 35 printf("%d\n",f[num[len+1]-1][0]/sum); 36 } 37 fclose(stdin);fclose(stdout); 38 return 0; 39 } 40