Roman is a young mathematician, very famous in Uzhland. Unfortunately, Sereja doesn't think so. To make Sereja change his mind, Roman is ready to solve any mathematical problem. After some thought, Sereja asked Roma to find, how many numbers are close to number n, modulo m.
Number x is considered close to number n modulo m, if:
- it can be obtained by rearranging the digits of number n,
- it doesn't have any leading zeroes,
- the remainder after dividing number x by m equals 0.
Roman is a good mathematician, but the number of such numbers is too huge for him. So he asks you to help him.
The first line contains two integers: n (1 ≤ n < 1018) and m (1 ≤ m ≤ 100).
In a single line print a single integer — the number of numbers close to number n modulo m.
104 2
3
223 4
1
7067678 8
47
In the first sample the required numbers are: 104, 140, 410.
In the second sample the required number is 232.
状态DP dp[S | (1 << j) ][(k * 10 + a[j])] += dp[S][k]; ( s 里不包括 第j 个元素)
dp[S][k] 代表 取s 代表 所取的元素集合,k代表对m的取模,则这个数组代表在这一状态的数目
1 #include <cstdio> 2 #include <cstring> 3 #include <algorithm> 4 #include <iostream> 5 #include <cmath> 6 #include <bitset> 7 8 using namespace std; 9 10 typedef long long ll; 11 12 #define maxn (1 << 18) 13 14 ll dp[maxn][105],fac[20]; 15 int s[105],num[10]; 16 int m,len = 0; 17 ll n; 18 19 20 21 void init() { 22 ll t = n; 23 while(t) { 24 s[len++] = t % 10; 25 num[t % 10]++; 26 t /= 10; 27 } 28 29 fac[0] = 1; 30 for(int i = 1; i <= 18; i++) { 31 fac[i] = fac[i - 1] * i; 32 } 33 34 35 36 for(int S = 1; S < (1 << len); S++) { 37 for(int j = 0; j < m; j++) { 38 dp[S][j] = 0; 39 } 40 } 41 } 42 43 void solve() { 44 init(); 45 46 dp[0][0] = 1; 47 48 for(int S = 0; S < (1 << len); ++S) { 49 for(int j = 0; j < len; ++j) { 50 if(!(S & (1 << j))) { 51 for(int k = 0; k < m; ++k) { 52 if(S || s[j]) 53 dp[S | (1 << j)][(k * 10 + s[j]) % m] 54 += dp[S][k]; 55 56 } 57 } 58 59 60 } 61 62 } 63 64 for(int i = 0; i < 10; i++) { 65 if(num[i] > 1) { 66 dp[(1 << len) - 1][0] /= fac[ num[i] ]; 67 } 68 69 } 70 printf("%I64d ",dp[(1 << len) - 1][0]); 71 72 73 } 74 75 int main () { 76 77 //freopen("sw.in","r",stdin); 78 79 scanf("%I64d%d",&n,&m); 80 81 solve(); 82 83 return 0; 84 85 86 87 }