并查集

并查集

class UnionFind{
      private int[] parents;
      UnionFind(int size){
            parents = new int[size];
            for(int i=0;i < size ;i++) parents[i] = i;
      }
      public int find(int x){
            return x==parents[x]?x:find(parents[x]);
      }  
      public void union(int x,int y){
            int xp = find(x);
            int yp = find(y);
            if(xp == yp) return;
            parents[xp] = yp;
      } 
      public boolean isConnect(int x,int y){
            return find(x) == find(y);
      }
}
posted @ 2020-11-06 14:50  BOTAK  阅读(52)  评论(0编辑  收藏  举报