图论专题 - 解题报告 - G

没啥好说的,排序后贪心,并查集判定连通,达成数量条件就可以输出。

#include
#define FOR(a, b, c) for(int a=b; a<=c; a++)
#define maxn 500005
#define maxm 55
#define hrdg 10007
#define zh 16711680
#define inf 2147483647
#define llinf 9223372036854775807
#define ll long long
#define pi acos(-1.0)
#define ls p<<1
#define rs p<<1|1
using namespace std;

int n, m, k, u, v, d, ans;
struct Edge{ int u, v, dis;} edge[maxn];

inline int read(){
    char c=getchar();long long x=0,f=1;
    while(c<'0'||c>'9'){if(c=='-')f=-1;c=getchar();}
    while(c>='0'&&c<='9'){x=x*10+c-'0';c=getchar();}
    return x*f;
}

int fa[maxn];			//想了一下还是压了并查集的行,我怎么看我这轮专题的代码那么冗长呢
inline int setfind(int x){ return x == fa[x] ? x : fa[x] = setfind(fa[x]);}
inline void setunion(int x,int y){ x = setfind(fa[x]); y = setfind(fa[y]); fa[x] = y;}
inline bool setcheck(int x,int y){ x = setfind(x); y = setfind(y); return x == y;}

bool cmp(Edge x, Edge y){ return x.dis < y.dis;}

int main()
{
    n = read(); m = read(); k = read();
    for (int i = 1; i <= m; i++)
    {
        u=read(); v=read(); d=read();
        edge[i] = {u, v, d};
    }
    for (int i = 1; i <= n; i++)
        fa[i] = i;
    sort(edge + 1, edge + 1 + m, cmp);
    for (int i = 1; i <= m; i++)
    {
        if (setcheck(edge[i].u, edge[i].v))
            continue;
        setunion(edge[i].u, edge[i].v);
        k++;
        ans += edge[i].dis;
        if (k == n)
            break;
    }
    cout << ans;
    return 0;
}

你可能感兴趣的:(解题报告)