BZOJ 1072: [SCOI2007]排列perm 状态压缩DP

1072: [SCOI2007]排列perm


Description

  给一个数字串s和正整数d, 统计s有多少种不同的排列能被d整除(可以有前导0)。例如123434有90种排列能
被2整除,其中末位为2的有30种,末位为4的有60种。

Input

  输入第一行是一个整数T,表示测试数据的个数,以下每行一组s和d,中间用空格隔开。s保证只包含数字0, 1
, 2, 3, 4, 5, 6, 7, 8, 9.

Output

  每个数据仅一行,表示能被d整除的排列的个数。

Sample Input

7
000 1
001 1
1234567890 1
123434 2
1234 7
12345 17
12345678 29

Sample Output

1
3
3628800
90
3
6
1398

HINT

在前三个例子中,排列分别有1, 3, 3628800种,它们都是1的倍数。

【限制】

100%的数据满足:s的长度不超过10, 1<=d<=1000, 1<=T<=15

题解:

  设定dp[i][k] 选取的书状态为i下mod d等于j的方案数

  显然有转移方程 dp[i|(1<<j)][(k*10+a[j]-'0')%d] += dp[i][k];这样时间跑三维 10*(1<<n)*d,空间(1<<n)*d

  最后记得去重

#include<iostream>
#include<cstring>
#include<cstdio>
#include<cmath>
#include<algorithm>
using namespace std;
const int N = 1e6+10, M = 1e3+11, inf = 2e9, mod = 1e9+7;
int dp[1<<11][M],d,T,p[N],c[N];
char a[N];
int main()
{
    c[0]=1;for(int i=1;i<=11;i++) c[i]=c[i-1]*i;
    scanf("%d",&T);
    while(T--)
    {
        scanf("%s%d",a,&d);
        int n = strlen(a);
        memset(p,0,sizeof(p));
        for(int i=0;i<n;i++) p[a[i]-'0']++;
        memset(dp,0,sizeof(dp));
        int U = (1<<n)-1;dp[0][0]=1;
        for(int i=0;i<=U;i++)
        {
            for(int j=0;j<n;j++)
            {
                if(!(i&(1<<j)))
                {
                    for(int k=0;k<d;k++)
                        dp[i|(1<<j)][(k*10+(a[j]-'0'))%d] += dp[i][k];
                }
            }
        }
        int ans = dp[U][0];
        for(int i=0;i<10;i++) ans/=c[p[i]];
        printf("%d
",ans);
    }
    return 0;
}
原文地址:https://www.cnblogs.com/zxhl/p/5654056.html