题解 P6274 【[eJOI2017]六】

· · 题解

系列。

代码头。

刚开始没开 long long WA了一发。

首先会发现两个数是否互质只与所包含的质因子种类有关,然后这个 N 最多六个质因子所以至多 2^6=64 种不同的质因子分布。

考虑用一个 64 位进制数存下一个分布,每一位表示与当前位所示分布不互质的数的个数。容易发现由于只有 0,1,2(<-表示已经炸了,即这个分布必须不存在)三种状态所以可以用三进制,但为了简化代码&减小常数采用四进制,用一个 __uint128_t 每两位一个分布存下来成为一个状态。

辅助部分:

typedef __uint128_t status;
int typecnt(status st,int type){
    return (st>>(type<<1))&3;
}
void addtype(status&st,int type){
    st+=status(1)<<(type<<1);
}

然后可以感性理解有用的状态数不会很多,所以直接记忆化搜索就完事了。

去头代码:

const modder mod=1e9+7;
typedef __uint128_t status;
struct hsh{
    size_t operator()(const status&stat)const{
        typedef unsigned long long ull;
        return hash<ull>()(stat&ULLONG_MAX)^hash<ull>()(stat>>64);
    }
};//unordered_map用的哈希函数
int typecnt(status st,int type){
    return (st>>(type<<1))&3;
}//计算一个状态内某个分布的不互质数的个数
void addtype(status&st,int type){
    st+=status(1)<<(type<<1);
}//把一个状态内某个分布的不互质数的个数加一
unordered_map<status,int,hsh>umap;//记忆化搜索
long long n,cnt[64]{1};//cnt表示某个分布对应的因子个数(建议联系下文理解)
int pcnt;//n的质因子数量
int dfs(status st){
    if(umap.count(st))return umap[st];//记忆化
    status init=st;//后面为了方便起见会直接操作st,放个init好复原
    long long ret=1;
    for(int toadd:range(1,1<<pcnt))if(typecnt(st=init,toadd)<=1){//如果这个状态还能加
        for(int i:range(1<<pcnt))
            if((i&toadd)&&typecnt(st,i)<=1)addtype(st,i);//非互质的分布对应位全部+1,可以发现只要满足上面那个还能加的条件,到这里一定不会挂掉
        ret+=cnt[toadd]*dfs(st);//递归暴搜
    }
    return umap[st=init]=ret%mod;
}
void initcnt(){//递推计算cnt
    for(long long i=2;i*i<=n;++i)if(!(n%i)){
        while(!(n%i))
            n/=i,++cnt[1<<pcnt];
        ++pcnt;
    }
    if(n>1)cnt[1<<pcnt]=1,++pcnt;//分解素因数
    for(int i:range(1,1<<pcnt))cnt[i]=(cnt[i&(i-1)]*cnt[i&-i])%mod;//计算cnt
}
signed main(){
    scanf("%lld",&n);
    initcnt();
    printf("%d\n",(dfs(0)-1)%mod);
    return 0;
}

目测不难看懂,如果无法理解的话可以私信或评论。

Over。