• 洛谷p1195(大水题,裸并查集)


    刚刚做了一道洛谷上的题,一道很水很水的裸并查集,直接上代码。

    题目:https://www.luogu.org/problemnew/show/P1195

    #include<iostream>
    #include<cstdio>
    #include<cstring>
    #include<algorithm>
    #define N 100000//好像开的有点大
    using namespace std;
    int n,m,k,fa[N],num,ans;
    struct node{
        int a,b,w;
    }e[N];
    int find(int x);//找父节点
    bool cmp(node x,node y)
    {
        return x.w<y.w;
    }
    int main()
    {
        cin>>n>>m>>k;
        for (int i=1;i<=m;i++)
        fa[i]=i;
        for (int i=1;i<=m;i++)
            cin>>e[i].a>>e[i].b>>e[i].w;
    sort(e+1,e+m+1,cmp);//按从小到大的顺序,貌似有种贪心的思想。。
        for (int i=1;i<=m;i++)
        {
            int na=find(e[i].a),nb=find(e[i].b);
            
            if (na==nb) continue;//如果已经在里面了,就不用再合并
            else {
                fa[na]=nb;
                ans+=e[i].w;
                num++;
            }//合并,并且更新答案
                if(num==n-k) {
                cout<<ans;
                return 0;
                }
        }
        cout<<"No Answer";
        return 0;
    }
    int find(int x)
    {
        if (fa[x]==x) return x;
        return fa[x]=find(fa[x]);
    }
  • 相关阅读:
    python module introduce
    python代码基
    20100911部署更新
    汉王ocr
    wsgi
    css布局模板
    Making a simple web server in Python.
    20100910更新部署
    tw.forms usage
    python web shell
  • 原文地址:https://www.cnblogs.com/LWJ2333/p/7889857.html
Copyright © 2020-2023  润新知