题解:P1195

· · 题解

P1195 题解

1.什么是生成树?

生成树定义:生成树就是在联通图内图里的一棵树

生成树性质:如果原图有 n 个节点,则任意一棵生成树内,一定只有 n 各节点,n-1 条边。

示例:

下图中的生成树可以是(单选)?

A.

B.

C.

D.

:::success[答案]

B

:::

2.什么是最小生成树?

最小生成树定义:就是在一个有权无向联通图内,所有最小生成树中,书上的总边权和最小的生成树(可能有多个)。

示例

下图中的生成树可以是(单选)?

A.

B.

C.

D.

:::success[答案]

D

:::

如何实现最小生成树?

关联题目:P3366

思路:

1.先对边数组按权值从小到大进行排序
struct edge{
    int u,v,w;
}
vector<edge> G;
bool cmp(edge x,edge y){
    return x.w<y.w;
}
int main(){
    //假设已经输入
    sort(G.begin(),G.end(),cmp);
    return 0;
}
2.接着遍历图上的每一条边
int main(){
    //已排序
    for(auto e:G){
        int u=e.u,v=e.v,w=e.w;
    }
    return 0;
}
3.判断 u 和 v 是否连通(并查集实现)
如果连通,加入这条边后,会形成一个环,这样就不是最小生成树了,所以不能加入这条边
如果不连通,则可以把该边加入最小生成树,sum 累加该边的边权
    for(auto e:G){
        int u=e.u,v=e.v,w=e.w;
        if(findRt(u)!=findRt(v)) sum+=w,cnt++;  //如果不连通,即可以加入最小生成树,sum累加w,边数+1
        //否则就不用管
    }
完整代码实现(P3366)
#include<bits/stdc++.h>
using namespace std;
const int N=1e5+5;
int n,m;
int fa[N];
int findRt(int x){
    if(fa[x]==x) return x;
    return fa[x]=findRt(fa[x]);
}
void merge(int x,int y){
    int fx=findRt(x);
    int fy=findRt(y);
    fa[fx]=fy;
}
struct node{
    int u,v,w;
};
bool cmp(node x,node y){
    return x.w<y.w;
}
vector<node> e;
int main(){
    cin>>n>>m;
    for(int i=1;i<=n;++i) fa[i]=i;
    for(int i=1;i<=m;++i){
        int u,v,w;
        cin>>u>>v>>w;
        e.push_back({u,v,w});
    }
    int ans=0,cnt=0;
    sort(e.begin(),e.end(),cmp);
    for(auto x:e){
        int u=x.u,v=x.v,w=x.w;
        if(findRt(u)!=findRt(v)){
            merge(u,v);
            ans+=w;
            cnt++;
            if(cnt==n-1){
                cout<<ans;
                return 0;
            }
        }
    }
    cout<<"orz";
    return 0;
}

2.本题实现

代码基本一样,只需将 cnt==n-1 换成 cnt==n-k 即可

完整代码:

#include<bits/stdc++.h>
using namespace std;
using i64=long long;
const int N=2e4+5;
int n,m,k,u,v,w;
int fa[N];
struct node{
    int u,v,w;
};
bool cmp(node x,node y){
    return x.w<y.w;
}
int findRt(int x){
    if(fa[x]==x) return x;
    return fa[x]=findRt(fa[x]);
}
void merge(int x,int y){
    fa[findRt(x)]=findRt(y);
}
vector<node> e;
int main(){
    cin>>n>>m>>k;
    if(n==k){
        cout<<"0";
        return 0;
    }
    for(int i=1;i<=n;++i) fa[i]=i; 
    for(int i=1;i<=m;++i){
        cin>>u>>v>>w;
        e.push_back({u,v,w});
    }
    int ans=0,cnt=0;
    sort(e.begin(),e.end(),cmp);
    for(auto x:e){
        int u=x.u,v=x.v,w=x.w;
        if(findRt(u)!=findRt(v)){
            merge(u,v);
            cnt++;
            ans+=w;
            if(cnt==n-k){
                cout<<ans;
                return 0;
            }
        }
    }
    cout<<"No Answer\n";
    return 0;
}

3.时间复杂度:

E \log_2 E+(E+V)\varphi(V)

Tips:其中E是边数,V是节点个数。

:::info[written by] ___6

这是本薄弱第一次写题解,如有任何问题请私信。

:::