跳到正文

题解

Mobile Phone Network-题解

Endt约 5 分钟
原文
文章信息与版本

文章信息

收录
2025年12月12日
更新
2025年12月12日
篇幅
约 5 分钟
题目
CF1023F

版本

  1. v2当前
  2. v1

Mobile Phone Network-题解

题意

给定 kk 条边权不定的边与 mm 边权确定的边,让 kk 条边在最小生成树中并最大化 kk 条边。

解法

既然要让 kk 条边在最小生成树内,那先将这些边加入这棵树,再用 Kruskal 让 mm 条边补全生成树。对于剩下的非树边,令端点为 xx 和 yy 边权为 ww,根据最小生成树的性质,生成树上 xx 到 yy 的路径边权都不能超过 ww,否则其中的一条边应由这条非树边代替。

问题转化为给多条树上路径与值 ww,使得每条路径上所有边的权值不超过 ww。树剖显然可以解决,但时空均劣,容易被卡掉。

可以让 ww 递增,那么每条边最多会更新最小值一次,用并查集维护已经更新的部分,时间复杂度可降到近似 O(n)O(n)。

代码

C++
#include<bits/stdc++.h>

#define  Int  long long int
#define  Pub  public
#define  rand  Rand
std::mt19937 rand(time(0));

using std::min;using std::max;
using std::swap;
const Int INF=1000000000000000;

int n,k,m;
std::map<std::pair<int,int>,bool> h;

int RD(){
    int x=0;char c=getchar();
    while(c>'9'||c<'0')c=getchar();
    while(c<='9'&&c>='0')x=(x<<3)+(x<<1)+c-'0',c=getchar();
    return x;
}
class Node{
Pub:std::vector<int> s;int fa;
    int dp;
}a[500005];

Int t[2000005];


void dfs(int x){
    if(h.find({x,a[x].fa})==h.end()&&h.find({a[x].fa,x})==h.end())t[x]=0;
    a[x].dp=a[a[x].fa].dp+1;
    for(int i:a[x].s){
        if(i==a[x].fa)continue;
        a[i].fa=x;
        dfs(i);
    }
}

class Edge{
Pub:int x,y;
    Int z;
    bool f;
}e[500005];
int fa[500005];
int fin(int x){
    if(fa[x]!=x)fa[x]=fin(fa[x]);
    return fa[x];
}
int FA[500005];
int FIN(int x){
    if(FA[x]!=x)FA[x]=FIN(FA[x]);
    return FA[x];
}
int main(){
    scanf("%d%d%d",&n,&k,&m);
    for(int i=1;i<=n;++i)fa[i]=FA[i]=i;
    for(int i=1,x,y;i<=k;++i){
        x=RD(),y=RD();
        fa[fin(x)]=fin(y);
        a[x].s.emplace_back(y);
        a[y].s.emplace_back(x);
        h[{x,y}]=1;
    }
    for(int i=1;i<=m;++i)e[i].x=RD(),e[i].y=RD(),e[i].z=RD();
    for(int i=1;i<=m;++i){
        if(fin(e[i].x)!=fin(e[i].y)){
            fa[fin(e[i].x)]=fin(e[i].y);
            a[e[i].x].s.emplace_back(e[i].y);
            a[e[i].y].s.emplace_back(e[i].x);
            e[i].f=1;
        }
    }
    std::fill(t,t+2000005,INF);

    dfs(1);
    for(int i=1;i<=m;++i){
        if(e[i].f==0){
            int x=e[i].x,y=e[i].y;
            while(x!=y){
                x=FIN(x),y=FIN(y);
                if(x==y)break;
                if(a[x].dp<a[y].dp)swap(x,y);
                t[x]=min(t[x],e[i].z);
                FA[x]=FIN(a[x].fa);
            }
        }
    }
    Int ans=0;
    for(int i=1;i<=n;++i)ans=min(INF,t[i]+ans);
    if(ans==INF)printf("-1");
    else printf("%lld",ans);

    return 0;
}
原文