Codeforces Round #235 (Div. 2) D. Roman and Numbers(如压力dp)

本文探讨了一个数学问题,即在给定的数字和模数条件下,找到所有可以由该数字重新排列而成、且与给定模数相除余数为0的数。通过状态压缩动态规划的方法解决这一问题,特别强调了多重排列的处理和去除重复计数的技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.


题意:给出一个数字num和m。问通过又一次排列num中的各位数字中有多少个数(mod m)=0,直接枚举全排列肯定不行,能够用状压dp来搞..

dp[S][k]表示选了num中的S且(mod m)=k的方案种数,初始条件dp[0][0]=1,转移方为dp[i|1<<j[(10*k+num[j])%m]+=dp[i}[k];,注意到是多重排列。所以还须要除去反复的。

代码例如以下:


#include <iostream>
#include <cstring>
using namespace std;

typedef long long ll;

ll dp[1<<18][100],c[20];//dp[S][k]表示选了num中的S且(mod m)=k的方案种数

int main(int argc, char const *argv[])
{
	char num[20];
	int m;
	while(cin>>num>>m) {

		memset(dp,0,sizeof dp);
		memset(c,0,sizeof c);
		dp[0][0]=1;

		ll div=1,sz=strlen(num),t=1<<sz;
		for(int i=0;i<sz;i++) {
			div*=(++c[num[i]-='0']);//可重排列最后要除的除数n1!*n2!*...nk!
		}

		for(int i=0;i<t;i++) {
			for(int j=0;j<sz;j++)if(!(i&1<<j)) {//集合S中不含j才转移
				if(num[j]||i){//至少一个不为0保证无前导0
					for(int k=0;k<m;k++) {
						dp[i|1<<j][(10*k+num[j])%m]+=dp[i][k];
					}
				}
			}
		}

		cout<<dp[t-1][0]/div<<endl;
	}
	return 0;
}


版权声明:本文博主原创文章。博客,未经同意不得转载。

转载于:https://www.cnblogs.com/mengfanrong/p/4854143.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值