lightoj 1021 - Painful Bases

来源:互联网 发布:全局session 丢失数据 编辑:程序博客网 时间:2024/06/06 22:25

As you know that sometimes base conversion is a painful task. But still there are interesting facts in bases.

For convenience let's assume that we are dealing with the bases from 2 to 16. The valid symbols are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, A, B, C, D, E and F. And you can assume that all the numbers given in this problem are valid. For example 67AB is not a valid number of base 11, since the allowed digits for base 11 are 0 to A.

Now in this problem you are given a base, an integer K and a valid number in the base which contains distinct digits. You have to find the number of permutations of the given number which are divisible by KK is given in decimal.

For this problem, you can assume that numbers with leading zeroes are allowed. So, 096 is a valid integer.

Input

Input starts with an integer T (≤ 100), denoting the number of test cases.

Each case starts with a blank line. After that there will be two integers, base (2 ≤ base ≤ 16) and K (1 ≤ K ≤ 20). The next line contains a valid integer in that base which contains distinct digits, that means in that number no digit occurs more than once.

Output

For each case, print the case number and the desired result.

Sample Input

Output for Sample Input

3

 

2 2

10

 

10 2

5681

 

16 1

ABCDEF0123456789

Case 1: 1

Case 2: 12

Case 3: 20922789888000




第一行输入n,k,第二行输入一个行字符串

然后这题的大意是给你一串没有相同的数字的数字串(有可能会有字母),问你用这些数字组成多少种n进制的排列可以被k整除,输出可能的种数。


这题是一个状压DP,第一开始竟然想成了数位DP,想了半天发现状态不好表示,最后发现每一个数字只能出现一次,所以直接用二进制表示第i个数有没有选过就可以表示状态了,这样就能看出来直接状压DP即可。


#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>using namespace std;char s[20];int a[20];long long dp[1<<16][20];int main(void){    int T,n,m,i,j,k;    scanf("%d",&T);    int c = 1;    while(T--)    {        scanf("%d%d",&n,&m);        scanf("%s",s);        int len = strlen(s);        for(i=0;i<len;i++)        {            if(s[i] >= '0' && s[i] <= '9')                a[i] = s[i] - '0';            else                a[i] = s[i] - 'A' + 10;        }        memset(dp,0,sizeof(dp));        dp[0][0] = 1;        for(i=0;i<(1<<len);i++)        {            for(j=0;j<m;j++)            {                if(!dp[i][j])                    continue;                for(k=0;k<len;k++)                {                    if(i&(1<<k))                        continue;                    dp[i|(1<<k)][(j*n+a[k])%m] += dp[i][j];                }            }        }        printf("Case %d: %lld\n",c++,dp[(1<<len)-1][0]);    }}


0 0
原创粉丝点击