codeforces 401D Roman and Numbers (数位dp)

D. Roman and Numbers

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.


解题思路:

不算是一道典型的数位dp问题,但是仔细分析后可以发现其内含的跟数位有关的特征,一个数能否被 m 整除跟它每一位上的数字有关,将n所有位的数字重排也是按位填充,所以可以采用数位dp解决这个问题。

dp[s][k] s表示n中各个位置上的数字使用情况,用二进制来表示填充情况,也算是一种状态压缩。 k表示到当前位对m取模的余数(带余除法)。

转移的时候需要注意一点,就是每一位填充的数字不要重复,这样会重复计算答案。所以在数位dp的时候每一位可以开一个数组记录一下当前位使用数字的情况。

AC代码:

/*
* @Author: wchhlbt
* @Last Modified time: 2017-09-13
*/

#include <bits/stdc++.h>

#define Fori(x) for(int i=0;i<x;i++)
#define Forj(x) for(int j=0;j<x;j++)
#define maxn 1000007
#define inf 0x3f3f3f3f
#define ONES(x) __builtin_popcount(x)
#define _  << "  " <<
using namespace std;

typedef long long ll ;
const double eps =1e-8;
const int mod = 1000000007;
const double PI = acos(-1.0);
int dx[5] = {0,0,1,-1,0};
int dy[5] = {1,-1,0,0,0};
inline int read(){ int cnt;    scanf("%d",&cnt);   return cnt;}

int bit[20];
ll dp[(1<<19)+7][107];
ll n,m;
int len;
ll dfs(int pos, int s, int k)
{
	if(pos<1){
		if(s==(1<<len)-1)	return (k==0);
		else	return 0;
	}
	if(dp[s][k]!=-1)	return dp[s][k];
	int flag[10];
	memset(flag,0,sizeof flag);
	ll res = 0;
	for(int i = 1; i<=len; i++){
		if((s &( 1<<(i-1) ))==0 && flag[bit[i]]==0){
			if(pos==len && bit[i]==0)	continue;//不能有前导0
			res += dfs(pos-1,s | (1<<(i-1)), (k*10+bit[i])%m) , flag[bit[i]] = 1;
		}
	}
	dp[s][k] = res;
	return res;
}

ll solve(ll n)//预处理函数,将所给定的数字,处理为每个位置上的数字(上界)
{
    len = 0;
    while(n)
    {
        bit[++len] = n%10;
        n /= 10;
    }
    return dfs(len, 0 , 0);;
}

int main()
{
	cin>>n>>m;
	memset(dp,-1,sizeof dp);
	cout << solve(n) << endl;
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值