CodeForces 401D. Roman and Numbers (状压DP)

Description
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 < 1e18) and m (1 ≤ m ≤ 100).

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

Examples
Input
104 2
Output
3

Input
223 4
Output
1

Input
7067678 8
Output
47

Solution
因为n 最大为18位,且 m <= 100, 所以可以采用状压DP来求解
定义 d p [ s ] [ k ] dp[s][k] dp[s][k] 为 各位数选用情况为 s s s , 余数为 k k k 时的方案数
转移方程:
dp[i][(k*10 + dig[j]) % m] += dp[i^(1<<j)][k];

注意因为同一种数字可能不止一个,所以答案可能会重复计算
一种方法是最后依次除以各数字数的阶乘,另一种是在dp时判断一下是否是用过的数字

Code

ll n,m;
ll dp[1<<18][107],a[20];
int dig[20],len,num[10];

int main(){
    scanf("%lld%lld",&n,&m);
    while(n){
        dig[len++] = n % 10;
        num[n % 10]++;
        n /= 10;
    }
    for(int i = 0;i < len;++i) 
       if(dig[i]) dp[1<<i][dig[i]%m] = 1;

    bool vis[10];clr(vis,false);
    for(int i = 0;i < (1 << len);++i){
        clr(vis,false);
        for(int j = 0;j < len;++j){
            if(i & (1<<j) && !vis[dig[j]]){
                vis[dig[j]] = true;
                for(int k = 0;k < m;++k)
                    dp[i][(k*10 + dig[j]) % m] += dp[i^(1<<j)][k];
            }
        }
    }
    printf("%lld\n", dp[(1 << len)-1][0]);
    return 0;
}
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值