Time Limit: 2 second(s) | Memory Limit: 32 MB |
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 | Output for Sample Input |
3
2 2 10
10 2 5681
16 1 ABCDEF0123456789 | Case 1: 1 Case 2: 12 Case 3: 20922789888000 |
题目链接:http://lightoj.com/volume_showproblem.php?problem=1021
题目大意:base表示base进制,给一个k(0 <= k <= 20),给一个base进制下的合法数,保证每位数字都不同,求这个数字的所有排列中是k的倍数的个数
题目分析:因为数字都不同,所以最多只有16位,因此可以状压做,dp[i][j]表示选数状态为i,模k为j的排列数个数,然后对一个合法状态扩展就是在前面加数字,取模的时候因为((x * base) + num[idx]) % k == ((x * base) % k + num[idx] % k) % k == (j * base + num[idx] % k ) % k所以转移方程就是
dp[i | (1 << idx)][(j * base + num[idx] % k) % k] += dp[i][j]
#include <cstdio>
#include <cstring>
#include <algorithm>
#define ll long long
using namespace std;
int const MAX = (1 << 16) + 5;
ll dp[MAX][25];
char s[25];
int num[25];
int main()
{
int T;
scanf("%d", &T);
for(int ca = 1; ca <= T; ca++)
{
int b, k;
scanf("%d %d", &b, &k);
scanf("%s", s);
int len = strlen(s);
memset(dp, 0, sizeof(dp));
for(int i = 0; i < len; i++)
num[i] = s[i] >= 'A' ? (10 + s[i] - 'A') : (s[i] - '0');
dp[0][0] = 1;
for(int i = 0; i < (1 << len); i++)
for(int j = 0; j < k; j++)
if(dp[i][j])
for(int idx = 0; idx < len; idx++)
if(!(i & (1 << idx)))
dp[i | (1 << idx)][(j * b + num[idx] % k) % k] += dp[i][j];
printf("Case %d: %lld\n", ca, dp[(1 << len) - 1][0]);
}
}