P9836 种树 题解

· · 题解

题目传送门:P9836 种树
在 我的博客 食用效果(并不会)更佳

思路

首先来看看一个数的因数个数怎么求,考虑质因数分解,对于正整数 x :

x=p_1^{a_1} \times p_2^{a_2} \times \cdots \times p_n^{a_n}

对于某个因数 x, 质因数 p_i 的幂次有 0 \sim a_i 共 a_i+1 种可能的值,根据乘法原理,质因数个数为:

(a_i+1) \times (a_2+1) \times \cdots \times (a_n+1)

设 a_{i,j} 为 p_i 的质因数 j 的指数,S_i 是 p_i 质因数的集合,
本题中树覆盖的距离为:

\prod_{i=1}^n \prod_{j \in S_i} (a_{i, j}+1)

再考虑施肥操作。将 p_i 乘 k 相当于给 p_i 质因数 x 的指数加上 k 的质因子 x 的指数。显然每次贪心加到最小的 a_{i,x} 上,让 a_{i,x} 尽量平均即可(参考面积最大的矩形是正方形)。

参考代码

#include <bits/stdc++.h>
#ifdef LOCAL
#   define Log(os, x) (os)<<"> "#x" = "<<(x)<<endl
#else
#   define Log(os, x)
#   define endl '\n'
#endif
using namespace std;
template <typename T> T qread(){
    T x=0; int f=1; char c=getchar();
    while(c<'0'||c>'9'){if(c=='-') f=-1; c=getchar();}
    while(c>='0'&&c<='9'){x=(x<<1)+(x<<3)+(c&15); c=getchar();}
    return x*f;
}
template <typename T> void qwrite(T x, char c, bool f){
    if(x<0){putchar('-'); x=-x;}
    static int s[50], top;
    do{s[top++]=x%10; x/=10;}while(x);
    while(top) putchar(s[--top]+'0');
    if(f) putchar(c);
}
const int MAXN=(int)1e4+10, MOD=998244353;

int n,w;
int p[MAXN];

int prime[MAXN], tot;
bool is_prime[MAXN];
void euler(int N){
    is_prime[1]=true;
    for(int i=2; i<=N; ++i){
        if(!is_prime[i]) prime[++tot]=i;
        for(int j=1; j<=tot&&prime[j]*i<=N; ++j){
            is_prime[i*prime[j]]=true;
            if(!(i%prime[j])) break;
        }
    }
}
// w的质因数
int idw[MAXN], cntw[MAXN], totw;

int ans=1;

int main(){
#ifdef LOCAL
    freopen("test.in", "r", stdin);
    freopen("test.out", "w", stdout);
#endif
    euler(MAXN-10);
    n=qread<int>(), w=qread<int>();
    for(int i=1; i<=n; ++i) p[i]=qread<int>();

    for(int i=1; i<=tot; ++i){
        if(!(w%prime[i])){
            idw[++totw]=prime[i];
            while(!(w%prime[i])){
                w/=prime[i];
                cntw[totw]++;
            }
        }
    }
    for(int i=1; i<=totw; ++i){
        // 赛时写的很慢的施肥qwq
        priority_queue<int, vector<int>, greater<int>> q;
        for(int j=1; j<=n; ++j){
            int cntcur=0;
            while(!(p[j]%idw[i])){
                p[j]/=idw[i];
                cntcur++;
            }
            q.push(cntcur);
        }
        for(int j=1; j<=cntw[i]; ++j){
            int tmp=q.top(); q.pop();
            q.push(tmp+1); 
        }
        while(!q.empty()){
            ans=1ll*ans*(q.top()+1)%MOD;
            q.pop();
        }
    }
    for(int i=1; i<=n; ++i){
        for(int j=1; j<=tot; ++j){
            int cntcur=0;
            while(!(p[i]%prime[j])){
                cntcur++;
                p[i]/=prime[j];
            }
            ans=1ll*ans*(cntcur+1)%MOD;
        }
    }
    qwrite(ans, '\n', true);

    return 0;
}