【https://www.luogu.com.cn/article/rb3t3ujj】

· · 题解

题面是求一个数集 \set{1,\dots, n} 的全部子集 a_i 乘积的 \varphi 的和。数据范围比较大,但是 a_i 值域意外的小,猜测最终做法会剩余一个消不掉的值域枚举,这在质数数论领域比较常见。

首先考虑欧拉函数的简单计算方式(\mathcal O(\sqrt n)):

\varphi(n)=n\prod_{p\mid n}\left(1-\frac{1}{p}\right)

这是什么?这是完全不与其含有的质数有因子的个数,也正好就是全部与 n 互质的数的个数。根据这个定义,我们可以得出一个针对值域的做法。考虑这个 \varphi 在此情境下可以存在的转化:当集合 S 加上一个数 a_i 时,其产生的贡献恰好是其存在的新的质数个数。

那么我们就可以写出一个很简单的状压 DP 做法。具体的,我们先把每个 a_i 都转化为其存在的质数(12\to 2,3),对于一个数,存在的贡献就是其集合个数。那么我们只需要设 f_{S} 为当前选中的质数,转移是容易的,直接统计每一个结果的答案,然后最后乘上贡献就是对的了。这个做法的时间复杂度取决于值域内的质数个数,设为 V,则时间复杂度就是 \mathcal O(n2^V)(口胡的没写代码,可能有问题)。

但是这个 V 在题面的数据范围是 430,不足以直接通过。考虑优化这个东西。根据质数筛的对称性质我们发现:只需要考虑 \le \sqrt{3000} 的质数,其他的至多存在一次。那么题目 n 这么设计肯定是有原因的,这种环境下恰好有 2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53 共 16 个质数(剩余质数 414 个)。那么我们只需要对这些质数统计,然后剩下的单独存。

这样看来实现就有些难度了。设超出 53 的质数(单独贡献)为 p。然后对于每一个数,按 p 分组。对于每一个组,有 DP:f_{0/1,S} 为是否选举 p 的贡献。然后对于更换新的 p,有 f_{1}\to f_{0}。那么这样就可以完整计算代价了。

最终时间复杂度为 \mathcal O(n2^{V}),其中 V=16。之前这里写的有点问题,但是由于最终对于每一个数,只会贡献到一个大质数位置上,所以枚举大质数这部分均摊是 \mathcal O(n) 的。

// #define File
#include<bits/stdc++.h>
#define ll long long
#define ld long double
#define fi first
#define se second
using namespace std;
const ll inf=1e12, P=998244353;
const int N=3e3+10, V=16, SV=(1<<16)+5, LP=414;
ll qp(ll a,ll b=P-2){
    ll res=1;
    for(;b;b>>=1,a=(a*a)%P) if(b&1) res=(res*a)%P;
    return res;
}
ll n, a[N], cont[SV], pre[N]; // cont[S]: 一个数字集合的贡献
int primes[]={2,3,5,7,11,13,17,19,23,29,31,37,41,43,47,53};
struct state{ int s; ll o; };
vector<state> sets[N]; 
set<int> last_primes;
int f[2][SV];
void solve(){
    cin>>n;
    for(int i=1;i<=n;++i) cin>>a[i];
    for(int i=1;i<=n;++i){
        int state=0, ori=a[i], big=a[i];
        for(int j=0;j<V;++j) 
            while(big%primes[j]==0){ state|=(1<<j); big/=primes[j]; }
        last_primes.insert(big); sets[big].push_back({state, ori});
        pre[big]=(big-1)%P*qp(big)%P; // 预处理大数贡献
    }
    for(int i=0;i<(1<<V);++i){
        cont[i]=1;
        for(int j=0;j<V;j++) if((i>>j)&1) 
            cont[i]=cont[i]*(primes[j]-1)%P*qp(primes[j])%P;
    }
    f[0][0]=1;
    for(auto v:last_primes){
        // 使用类似背包的形式来做这个东西
        for(auto nums:sets[v]){
            int state=nums.s; ll ori=nums.o;
            for(int i=(1<<V)-1;~i;--i){
                ll newMul=cont[(i|state)^i]*ori%P;
                ll newState=i|state;
                (f[1][newState]+=newMul*f[1][i]%P)%=P;
                if(v>1) newMul=newMul*pre[v]%P;
                (f[1][newState]+=newMul*f[0][i]%P)%=P;
            }
        }
        for(int i=0;i<(1<<V);++i) // f[1] -> f[0]
            (f[0][i]+=f[1][i])%=P, f[1][i]=0;
    }
    ll ans=0;
    for(int i=0;i<(1<<V);++i)
        ans=(ans+f[0][i])%P;
    cout<<ans;
    return;
}
int main(){
    #ifdef File
        freopen("math.in","r",stdin);
        freopen("math.out","w",stdout);
    #endif
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int T=1; // cin>>T;
    while(T--) solve();
    return 0;
}