[BZOJ1072] [SCOI2007] 排列perm - dfs/dp

    看网上全是状压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;
}


  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值