题解:P14918 [GESP202512 五级] 相等序列

· · 题解

P14918 [GESP202512 五级] 相等序列题解

看到一个水题,过来打一下。
一个很明显的贪心
每一次操作相当于对某一个数乘或除一个质数,则考虑对每一个数进行质因数分解,然后用中位数计算需要操作的次数就行了。
对于一个样例:
4
5 18 32 21 | |2 |3 |5 |7 | |:-:|:-:|:-:|:-:|:-:| |5 |0 |0 |1 | 0 | |18 |1 |2 |0 |0 | |32 |6 |0 |0 |0 | |21 |0 |1 |0 |1 |

排序后就是这样的:

2 3 5 7
6 2 1 1
1 1 0 0
0 0 0 0
0 0 0 0

找每一个序列的中位数就行,如2序列的中位数就是1(或0),而5序列的中位数就是0

#include<bits/stdc++.h>
using namespace std;
int n;
int x;
bool f[100007];
map<int,vector<int>>v;//前一个下标指的是质因数,后一个是这个质因数每个的个数 
int main(){
    ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
    cin>>n;
    for(int i=2;i<=n;i++){
        if(f[i]) continue;
        for(int j=2*i;j<=n;j+=i) f[j]=1;
    }//埃氏筛 
    for(int i=1;i<=n;i++){
        cin>>x;
        for(int j=2;j*j<=x;j++){
            int cnt=0;
            while(x%j==0&&!f[j]) x/=j,cnt++;
            v[j].emplace_back(cnt);
        }
        if(x>1) v[x].emplace_back(1);
    }//分解质因数 
    int ans=0;
    for(auto it:v){
        vector<int>cur=it.second;
        sort(cur.begin(),cur.end());//排序,方便找中位数 
        int mid;
        if(n/2>cur.size()) mid=0; //中位数是0,的情况
        else mid=cur[cur.size()-n/2];//中位数非零,于是在cur的第cur.size()-n/2+1个,对应下标就是这个
        for(int num:cur) ans+=abs(num-mid);//有数字的操作 
        ans+=(n-cur.size())*mid;//加上剩余为0的操作数 
    }
    cout<<ans;
    return 0;
}