Union-find set
32. Union-find set
In order to complete the data structure,I use the following four steps:
1. Initial
int f[max];
inline void init(int n)
{
    while(n--)
    {
        f[i] = i;
    }
}
2. Find
int find(int x)
{
    if(f[x] == x)
    {
        return x;
    }
    else
        return find(f[x]);
}
3. Merge
inline void merge(int i,int j)
{
    f[find(i)] = find(j);
}
4. Path compression
int find(int x)
{
    return x == f[x] ? x : (f[x] = find(f[x]));
}
5. A example for the Union-find set set
1. Please click this link :Question
2. Code for the question
#include<bits/stdc++.h>
using namespace std;
#define maxn 100005
typedef struct 
{
    int r;
    int index;
    int t;
}mf;
int f[maxn];
mf a[maxn];
int n,m,counts=1;
inline bool cmp(const mf x,const mf y)
{
    if(x.t<y.t) return true;
    else return false;
}
inline void init(int num)
{
    num++;
    while(num--)
    {
        f[num]=num;
    }
}
int findm(int x)
{
    return x == f[x] ? x : (f[x] = findm(f[x]));//Path compression
}
void merge(int j,int i)
{
    int fa = findm(i),fb = findm(j);
    if(fa!=fb)  {f[fb] = fa;n--;}
}
int main()
{
    scanf("%d %d",&n,&m);
    init(n);
    int x,y,time;
    for(int i=1;i<=m;i++)
    {
        cin>>x>>y>>time;
        a[i].r=x,a[i].index=y,a[i].t=time;    
    }
    sort(a+1,a+m+1,cmp);
    bool flag=false;
    for(int j=1;j<=m;j++)
    {
        merge(a[j].r,a[j].index);
        if(n == 1) {cout<<a[j].t; f[0]=1;break;}
    }
    if(f[0]==0) cout<<"-1";
    return 0;
}

 
                
             
         浙公网安备 33010602011771号
浙公网安备 33010602011771号