codeforces 401D Roman and Numbers(状态压缩)

       题目意思很简单,给定两个数字 n (1 ≤ n < 1018) and m (1 ≤ m ≤ 100),然后对这个数字n进行shuffle,也就是重排,问存在多少个数字,使得该数字被m整除。

       想法还是比较简单的,首先我们定义状态dp[i][j],其中i表示所用了数字位的集合,j表示对应数字位组合出来的被m整除后的余数,dp状态记录该集合和该余数对应出现的计数。所有的状态为dp[1<<len][m],len为n的长度。

  1. 首先我们对n进行分解,记录各个数字(0-9出现的次数)和n的每一位的数字
  2. 很简单枚举状态进行转移,需要注意由于不能是前导0开头,所有在数字集合为空,并且现在枚举数字为j的时候需要continue。其中初始化状态dp[0][[0]=1,表示空集余数为0的计数为1
  3. 对于最后到状态dp[1<<len -1][0]需要除去每个数字出现次数的全排列
#include <cstdio>
#include <iostream>
#include <string>
#include <utility>
#include <algorithm>
#include <map>
using namespace std;

typedef long long ll;
const int MAXN = 1<<18;
const int INF = 1e9;
const ll MOD = 1000000007;
bool ids[MAXN];

ll dp[MAXN][100];

int bits[20];
int repeat[10];
int cclen(ll x){
	int ret =0;
	while(x){
		bits[ret] = x%10;
		repeat[x%10]++;
		x/=10;
		ret++;
	}
	return ret;
}
ll jie(ll x){
	if(!x) return 1;
	return x*jie(x-1);
}
int main(){
	ll n,m;
	cin>>n>>m;
	int len = cclen((n));

	dp[0][0] =1;
	//for(int i =0;i<len;i++) cout<<bits[i];
	//cout<<endl;
	for(int j=0;j<(1<<len);j++){
		for(int k=0;k<m;k++){
			for(int i =0;i<len;i++){
				if(j==0&&bits[i]==0) continue;
				if(j&(1<<i)) continue;

				int nextstate = j|(1<<i);
				int nextremind  = (k*10 + bits[i])%m;
				dp[nextstate][nextremind] += dp[j][k];
				//if(dp[nextstate][nextremind]<dp[j][k]) cout<<"dddd"<<endl;
			}
		}
	}

	//cout<<dp[(1<<len)-1][0]<<endl;
	for(int i=0;i<10;i++){
		dp[(1<<len)-1][0]/=jie(repeat[i]);
	}
	cout<<dp[(1<<len)-1][0]<<endl;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值