codeforce 954 div3 G2题

思路:

质因子分解可以顺着分解,也可以逆着分解

即找到每一个数字的倍数,再找到每一个数字的因数

cpp 复制代码
const int N = 5e5+10;
vector<int> ff[N];
vector<int> f[N];
vector<int> g[N];

void solve(){
    int n;
    cin>>n;
    vector<int> nums(n+1,0);
    ll ans = 0;
    for(int i = 1;i<=n;i++){
        cin>>nums[i];
    }
    for(int i = 1;i<=n;i++){
        int w = gcd(i,nums[i]);
        int x = i/w,y = nums[i]/w;
        //cout<<x<<" "<<y<<" eeeeee"<<endl;
        if(nums[i]%i == 0)  ans--;
        f[x].emplace_back(y);
        g[y].emplace_back(x);
    }
    vector<int>cnt(n+1,0);
    for(int i = 1;i<=n;i++){
        int m = f[i].size();
        if(m == 0)  continue;
        sort(f[i].begin(),f[i].end());
        for(int j = i;j<=n;j+=i){
            for(auto x : g[j]){
                cnt[x]++;
            }
        }
        for(int j = 0;j<m;j++){
            int k = 1;
            while(j<m-1 && f[i][j] == f[i][j+1]){
                j++;
                k++;
            }
            int y = f[i][j];
            ll sum = 0;
            for(auto son : ff[y]){
                sum += cnt[son];
            }
            sum *= k;
            ans += sum;
        }


        for(int j = i;j<=n;j+=i){
            for(auto x : g[j]){
                cnt[x]--;
            }
        }
    }
    for(int i = 1;i<=n;i++){
        f[i].clear();
        g[i].clear();
    }
    cout<<ans/2<<endl;
}
相关推荐
浮灯Foden43 分钟前
算法-每日一题(DAY13)两数之和
开发语言·数据结构·c++·算法·leetcode·面试·散列表
淡海水1 小时前
【原理】Struct 和 Class 辨析
开发语言·c++·c#·struct·class
西工程小巴1 小时前
实践笔记-VSCode与IDE同步问题解决指南;程序总是进入中断服务程序。
c语言·算法·嵌入式
Tina学编程2 小时前
48Days-Day19 | ISBN号,kotori和迷宫,矩阵最长递增路径
java·算法
Moonbit2 小时前
MoonBit Perals Vol.06: MoonBit 与 LLVM 共舞 (上):编译前端实现
后端·算法·编程语言
青草地溪水旁2 小时前
UML函数原型中stereotype的含义,有啥用?
c++·uml
青草地溪水旁2 小时前
UML函数原型中guard的含义,有啥用?
c++·uml
百度Geek说3 小时前
第一!百度智能云领跑视觉大模型赛道
算法
big_eleven3 小时前
轻松掌握数据结构:二叉树
后端·算法·面试
big_eleven3 小时前
轻松掌握数据结构:二叉查找树
后端·算法·面试