暑假集训周总结第四篇(8.14-8.21)

最小生成树

朴素版prim算法


#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define int long long
typedef pair<int,int> PII;
const int N=2e5+10;
const int INF=0x3f3f3f3f3f3f3f3f;

int g[505][505];
int d[505];
int n,m;
bool st[505];

int prim()
{
    
    memset(d,0x3f,sizeof(d));
    d[1]=0;
    int res=0;
    for(int i=0;i<n;i++)
    {
        int t=-1;
        for(int j=1;j<=n;j++)
        {
            if(!st[j] && (t==-1 ||d[t]>d[j]))
            t=j;
        }
        if(d[t]==INF)return INF;
        res+=d[t];
        
        st[t]=true;
        for(int j=1;j<=n;j++)
        d[j]=min(d[j],g[t][j]);
    }
    return res;
}
void solve()
{
    cin>>n>>m;
    memset(g,0x3f,sizeof(g));
    int a,b,c;
    while(m--)
    {
        cin>>a>>b>>c;
        g[a][b]=g[b][a]=min(g[a][b],c);
    }
    int tt=prim();
    if(tt==INF)
    {
        cout<<"impossible"<<endl;
    }
    else cout<<tt<<endl;

}
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int T = 1;
    //cin >> T;
    while (T--)
        solve();
    return 0;
}

Kruskal算法

并查集+贪心

#include <bits/stdc++.h>
using namespace std;
#define endl "\n"
#define int long long
typedef pair<int,int> PII;
const int N=1e5+10;
const int M=2e5+10;
const int INF=0x3f3f3f3f3f3f3f3f;
int n,m;
int p[N];//并查集部分
struct node
{
    int a;
    int b;
    int c;
    bool operator < (const node &W )const
    {
        return c<W.c;
    }
}edge[M];//存边
int find(int x)
{
    if(p[x]!=x) p[x]=find(p[x]);
    return p[x];
}
void solve()
{
    
    cin>>n>>m;
    for(int i=1;i<=n;i++)
    {
        p[i]=i;
    }//并查集初始化
    int u,v,w;
    for(int i=1;i<=m;i++)
    {
        cin>>u>>v>>w;
        edge[i].a=u;
        edge[i].b=v;
        edge[i].c=w;
    }//存边
    sort(edge+1,edge+1+m);//排序
    int cnt=0,res=0;
    for(int i=1;i<=m;i++)
    {
        int aa=edge[i].a,bb=edge[i].b,cc=edge[i].c;
        aa=find(aa);
        bb=find(bb);
        if(aa!=bb)//如果a,b不连通
        {
            
            p[aa]=bb;//连边a,b
            res+=cc;//最小生成树权值
            cnt++;//计数加了多少边
        }
    }
    if(cnt<n-1)cout<<"impossible"<<endl;//不构成树
    else cout<<res<<endl;
}
signed main()
{
    ios::sync_with_stdio(0);
    cin.tie(0);
    cout.tie(0);
    int T = 1;
    //cin >> T;
    while (T--)
        solve();
    return 0;
}

  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值