1072: [SCOI2007]排列perm
Time Limit: 10 Sec Memory Limit: 162 MBSubmit: 1350 Solved: 835
[ Submit][ Status][ Discuss]
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
000 1
001 1
1234567890 1
123434 2
1234 7
12345 17
12345678 29
Sample Output
1
3
3628800
90
3
6
1398
3
3628800
90
3
6
1398
HINT
在前三个例子中,排列分别有1, 3, 3628800种,它们都是1的倍数。
【限制】
100%的数据满足:s的长度不超过10, 1<=d<=1000, 1<=T<=15
最后答案即为f[(1<<n)-1][0].
坑点:要注意n个数字不一定全部不同,所以要除以相同的数的个数的阶乘。
代码:
<span style="font-size:18px;">#include<iostream>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#define ll long long
using namespace std;
int read()
{
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();}
return x*f;
}
int n,d;
string s;
int f[(1<<10)+10][1010],cnt[10],A[10],lim,len,ans;
int main()
{
n=read();
for(int i=1;i<=n;i++)
{
cin>>s;d=read();
lim=1<<(len=s.length());
memset(f,0,sizeof(f));memset(cnt,0,sizeof(cnt));
for(int j=0;j<len;j++)cnt[A[j]=s[j]-'0']++;
f[0][0]=1;
for(int S=0;S<lim;S++)
for(int j=0;j<d;j++)
for(int k=0;k<len;k++)
if(!(S&(1<<k)))f[S|(1<<k)][(10*j+A[k])%d]+=f[S][j];
ans=f[lim-1][0];
for(int j=0;j<10;j++)
for(int k=1;k<=cnt[j];k++)ans/=k;
cout<<ans<<endl;
}
}</span>