P8207 题解

· · 题解

考虑下怎么减少边数。去掉无效边。

首先连两条边 x,y 的代价是 \frac{x \times y}{\gcd(x,y)},考虑枚举 \gcd(x,y) = w 后对于 w \times i,w \times j 以 w \times i \times j 的代价连边,这样包含了一些不优边和所有优秀边(w = \gcd(x,y) 的 x,y),所以对正确性无影响。

不妨令 mi 为 [L,R] 中 w 的最小倍数除以 w 的结果,在 w \times i,w \times j 连边前,你发现 w \times i,w \times j 都会已经与 w \times mi 联通(kruskal 贪心地从小往大加边),所以只用考虑所有 wi 连出的边即可,因此总边数是 O((R-L) \log (R-L)) 的,再跑一遍 kruskal 即可做到 O((R-L) \log^2 (R-L))。

#include<bits/stdc++.h>
#define int long long
using namespace std;
const int maxn =4e6+100;
int tot;
struct node{
    int u,v,w;
}edge[maxn];
bool cmp(node a,node b){
    return a.w<b.w;
}
int fa[maxn];
int found(int u){
    if(fa[u]==u){
        return u;
    }
    else{
        return fa[u]=found(fa[u]);
    }
}
int res=0;   hg
signed main(){
    int l,r;
    cin>>l>>r;
    for(int i=l;i<=r;i++) fa[i]=i;
    for(int i=1;i<=r;i++){
        int v=ceil(l*1.0/i)*i;
        for(int j=ceil(l*1.0/i)*i;j<=r;j+=i){
            if(v!=j){
                edge[++tot].u=v;
                edge[tot].v=j;
                edge[tot].w=v*j/__gcd(v,j);
            }
        }
    }
    sort(edge+1,edge+tot+1,cmp);
    for(int i=1;i<=tot;i++){
        int u=edge[i].u;
        int v=edge[i].v;
        int w=edge[i].w;
        if(found(u)!=found(v)){
            //cout<<u<<' '<<v<<' '<<w<<'\n';
            fa[found(u)]=found(v);
            res+=w;
        }
    }
    cout<<res;
}