1158 - Anagram Division
Time Limit: 2 second(s) | Memory Limit: 32 MB |
Given a string s and a positive integer d you have to determine how many permutations of s are divisible by d.
Input
Input starts with an integer T (≤ 200), denoting the number of test cases.
Each case contains a string s (1 ≤ slength ≤ 10) and an integer d (1 ≤ d ≤ 1001). s will only contain decimal digits.
Output
For each case, print the case number and the number of permutations of s that are divisible by d.
Sample Input | Output for Sample Input |
3 000 1 1234567890 1 123434 2 | Case 1: 1 Case 2: 3628800 Case 3: 90 |
PROBLEM SETTER: ABDULLAH AL MAHMUD
SPECIAL THANKS: JANE ALAM JAN (SOLUTION, DATASET)
#pragma comment(linker, "/STACK:1024000000,1024000000")
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<stack>
#include<vector>
#include<set>
#include<map>
#define L(x) (x<<1)
#define R(x) (x<<1|1)
#define MID(x,y) ((x+y)>>1)
#define bug printf("hihi\n")
#define eps 1e-8
typedef long long ll;
using namespace std;
#define INF 0x3f3f3f3f
#define N 11
int p[11];
char c[N];
int dp[1<<N][1005];
int n,mod;
int vis[N];
void inint()
{
p[0]=1;
for(int i=1;i<N;i++)
p[i]=p[i-1]*i;
}
int dfs(int cur,int le)
{
// printf("%d\n",cur);
if(cur==(1<<n)-1) return le ? 0:1;
if(cur>=(1<<n)) return 0;
if(dp[cur][le]!=-1) return dp[cur][le];
dp[cur][le]=0;
for(int i=0;i<n;i++)
{
if(cur&(1<<i)) continue;
dp[cur][le]+=dfs(cur|(1<<i),(le*10+c[i]-'0')%mod);
}
return dp[cur][le];
}
int main()
{
inint();
int i,j,t,ca=0;
scanf("%d",&t);
while(t--)
{
scanf("%s%d",c,&mod);
n=strlen(c);
memset(vis,0,sizeof(vis));
int te=1;
for(int i=0;i<n;i++)
vis[c[i]-'0']++;
for(i=0;i<=9;i++)
te=te*p[vis[i]];
memset(dp,-1,sizeof(dp));
printf("Case %d: %d\n",++ca,dfs(0,0)/te);
}
return 0;
}