题解 CF1454D 【Number into Sequence】

· · 题解

根据题干进一步考虑最终得到的数列中数字的性质。

首先注意到最终数列中的数字满足: \prod_{i=1}^{k}a_i=n

分析得出:最终数列中的数字都是 n 的因数。

回到题干,我们注意到一个很奇怪的要求: \forall i \in [2,n] : a_i \ \bmod \ a_{i-1} = 0

由这个要求,首先可以推断出的是 a_{i-1} \le a_i 。因为如果 a_{i-1} > a_i 则必然有 a_i \ \bmod \ a_{i-1} = a_i 又因为有要求 \forall i \in a , i>1 所以显然不存在 a_{i-1} > a_i 。那么得出最终的数列一定的单调不下降子序列。

把上述两个结论放在一起看,再结合题目中最终序列的长度最长这一要求,我们发现,显然当 \forall i \in [2,n-1] : a_i \ = \ a_{i-1} 时答案更优。

我们知道,对于任意正整数 n 可以质因数分解得到 n = p_1^{c_1} \times p_2^{c_2} \times p_3^{c_3} \times ... \times p_m^{c_m} 的形式。由上述结论,我们得出: 我们要找到最大的 c_i 以及对应的 p_i 然后用 p_i 填充数列的前 c_i-1 项,最后一项则是 \frac {n}{p_i^{c_i-1}} 。 这样得出的数列就是最长数列。

那么我们只要用 O(\sqrt n) 的时间找到 n 的质因数分解中 c_i 最大的 p_i 即可。注意对于质数的情况要特判即可。

代码如下:

#include<iostream>
#include<cstdio>
#define ll long long
#define rgt register ll
using namespace std;

ll n,mxcnt,mxd,td,tcnt;

int main(){
    int test;
    scanf("%d",&test);
    while(test--){
        scanf("%lld",&n);
        mxd=n; mxcnt=0;
     //先假设 n 为质数

        for(rgt i=2;i*i<=n;i++){
            if(n%i==0){  //找到一个因数
                td=n;
                tcnt=0;
                while(td%i==0){  //尝试分解
                    td/=i;
                    tcnt++;
                }
                if(tcnt>mxcnt){  //更新答案
                    mxcnt=tcnt-1;
                    mxd=i;
                }
            }
        }

        printf("%lld\n",mxcnt+1);  //输出序列长度
        for(rgt i=1;i<=mxcnt;i++){
            printf("%lld ",mxd);  //输出拆得的质因数 Pi
            n/=mxd;
        }
        printf("%lld\n",n);  //输出 n/pi^(ci-1)
    }
    return 0;
}