codeforces #235 D. Roman and Numbers 题解

转载请注明:http://blog.csdn.net/jiangshibiao/article/details/23100595

【原题】

D. Roman and Numbers
time limit per test
4 seconds
memory limit per test
512 megabytes
input
standard input
output
standard output

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.

Input

The first line contains two integers: n (1 ≤ n < 1018) and m (1 ≤ m ≤ 100).

Output

In a single line print a single integer — the number of numbers close to number n modulo m.

Sample test(s)
input
104 2
output
3
input
223 4
output
1
input
7067678 8
output
47
Note

In the first sample the required numbers are: 104, 140, 410.

In the second sample the required number is 232.



【大意】给你一个n,让你找有多少x满足:x mod m=0。其中x是n的一个排列。重复的只计算一种。

【分析】这真是一道状态压缩的好题目。什么是状态压缩呢?就是把一个状态串压成一个十进制数。在这题里,对于n中的每一位数,都能表示成0或1(取或是不取)。而且总的状态数只有2^len-1(len是n的位数),因此我们可以用DP推出每一种状态。f[i][j]表示在i这种状态(01串的十进制形式),余数为j时的方案数。显然,如果我想取当前的数第K个数——dight[k],f[i][j]就能推到f[i+2^(k-1)][(j*10+dight[k])%m]。当然,要注意这个位置是否已经用过,同时也要注意数字的判重情况。

【代码】

#include
#include
using namespace std;
const int size=19;
bool flag[10];
long long dight[size],f[1<

你可能感兴趣的:(codeforces,题解)