1. 程式人生 > >bzoj1072【SCOI2007】排列perm

bzoj1072【SCOI2007】排列perm

solved 個數 get _id color problems bsp strlen article

1072: [SCOI2007]排列perm

Time Limit: 10 Sec Memory Limit: 162 MB
Submit: 1479 Solved: 928
[

id=1072" style="color:blue; text-decoration:none">Submit][Status][

id=1072" style="color:blue; text-decoration:none">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

Sample Output

1
3
3628800
90
3
6
1398

HINT

在前三個樣例中。排列分別有1, 3, 3628800種,它們都是1的倍數。



【限制】

100%的數據滿足:s的長度不超過10, 1<=d<=1000, 1<=T<=15

Source




狀壓DP題目

f[i][j]表示狀態為i,余數為j的方案數。




#include<iostream>
#include<cstdio>
#include<cstring>
#include<cmath>
#include<cstdlib>
#include<algorithm>
#define F(i,j,n) for(int i=j;i<=n;i++)
#define D(i,j,n) for(int i=j;i>=n;i--)
#define ll long long
using namespace std;
int t,d,n,ans;
int f[1050][1005],cnt[20],fac[20],g[1050],p[20];
char s[20];
inline 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;
}
inline int calc(int x)
{
	int ret=0;
	while (x){ret+=x&1;x>>=1;}
	return ret;
}
inline void dp(int x)
{
	F(i,0,n-1) if ((1<<i)&x)
	{
		int tmp=p[g[x]-1]%d*(s[i]-'0')%d;
		F(j,0,d-1) f[x][(j+tmp)%d]+=f[x^(1<<i)][j];
	}
}
int main()
{
	fac[0]=1;
	F(i,1,10) fac[i]=fac[i-1]*i;
	p[0]=1;
	F(i,1,10) p[i]=p[i-1]*10;
	F(i,0,1023) g[i]=calc(i);
	t=read();
	while (t--)
	{
		memset(f,0,sizeof(f));
		scanf("%s%d",s,&d);
		n=strlen(s);
		f[0][0]=1;
		F(i,1,(1<<n)-1) dp(i);
		ans=f[(1<<n)-1][0];
		memset(cnt,0,sizeof(cnt));
		F(i,0,n-1) cnt[s[i]-'0']++;
		F(i,0,9) ans/=fac[cnt[i]];
		printf("%d\n",ans);
	}
}


bzoj1072【SCOI2007】排列perm