看网上全是状压DP……我直接DFS的啊,带链表优化完之后一个数据点最多650W次DFS。如果怕被卡,完全可以栈手工模拟……
DP做法就是F[i][j]代表状态为i,余数为j的方案数。有点类似hash?ORZ,不过蒟蒻还是用DFS水过了- - 。
#include"stdio.h"
#include"iostream"
#define rep(f,a,b) for(f=a;f<=b;f++)
using namespace std;
struct node{
int w; node*next;
node(){};
node(int _w,node*_n){
w=_w; next=_n;
}
} *head=new node(-1,NULL);
int a[15],len,mod,ans;
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 void readchar(){
char ch=getchar();
for (;head->next->next;){
node *a=head->next;
head->next=a->next;
delete a;
}
while(ch<'0'||ch>'9'){ch=getchar();}
while(ch>='0'&&ch<='9'){
head->next=new node(ch-'0',head->next);
ch=getchar(); len++;
}
}
void dfs(int l){
if(l==len) {
int j,m=0; rep(j,1,len-1) m=(m*10+a[j])%mod;
m=m*10+head->next->w; if(m%mod==0) ans++; return ;
}
bool cho[10]={false};
for(node *i=head;i->next->next;){
while(cho[i->next->w]){
i=i->next;
if(i->next->w==-1) return;
}
node *p=i->next; a[l]=p->w; cho[p->w]=true;
i->next=i->next->next; dfs(l+1);
i->next=p; i=p;
}
}
void work(){
readchar(); mod=read();
dfs(1); printf("%d\n",ans);
}
int main(){
head->next=new node(-1,NULL);
int T,i; T=read();
rep(i,1,T) work(),ans=len=0;
return 0;
}