LightOJ

来源:互联网 发布:ehviewer一样的软件 编辑:程序博客网 时间:2024/06/11 02:56

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 K. K 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
3

2 2
10

10 2
5681

16 1
ABCDEF0123456789
Sample Output
Case 1: 1
Case 2: 12
Case 3: 20922789888000

题意

给定一个 base进制 以及数k 然后给出一个合法的base进制数
问:用这个给定数中的数字,进行排列组合,可以得到多少个k的倍数(在base进制下)

分析

因为base<=16 k<=20, 然后又是取模的题,比较容易想到状态压缩。
定义状态:dp[i][j] 表示集合i 中的数 对k 取模 余 j 的方案数【听着好绕、、】
转移:这里是用已有的状态去刷新未来的状态。对于当前状态i,如果i集合中不包括某一个数,那么这个数就可以加到这个集合能够组成的所有情况的最末尾那么就可以更新新的集合[i | (1<-idx)]
转移方程:
dp[i | (1<-idx)][ (j* base + num[idx] )%k]+=dp[i][j];

ps: +-号优先级高于左移右移- - 导致了一个bug找了半天

#include <iostream>#include <cstdio>#include <cmath>#include <cstring>#include <algorithm>using namespace std;const int INF=0x3f3f3f3f;char s[20];int num[20];long long dp[1<<16][20];int base,k;int main(){    freopen("in.txt","r",stdin);    int T,cas=0;    scanf("%d",&T);    while(T--){        scanf("%d%d",&base,&k);        scanf("%s",s);        int len=strlen(s);        for(int i=0;i<len;i++)            if(s[i]>='A' && s[i]<='Z') num[i]=10+s[i]-'A';            else num[i]=s[i]-'0';//      for(int i=0;i<len;i++) cout<<num[i]<<' ';        memset(dp,0,sizeof dp);        dp[0][0]=1;        for(int i=0;i<(1<<len)-1;i++){   // - 号优先级高于<< .....debug了半天             for(int j=0;j<k;j++){                if(dp[i][j]==0) continue;                for(int idx=0;idx<len;idx++){                    if( (i & (1<<idx))==0 ){                        dp[i | (1 << idx)][(j*base+num[idx]) % k]+=dp[i][j];                    }                }            }        }//      cout<<len<<"*"<<endl;        printf("Case %d: %lld\n",++cas,dp[(1<<len)-1][0]);    }    return 0;}