Algs4-1.5.20动态生长with Array

1.5.20动态生长。使用链表或大小可变的数组实现加权quick-union算法,去掉需要预先知道对象数量的限制。为API添加一个新方法netwSite(),它应该返回一个类型为int的标识符。
public class WeightedQuickUnionUFofDynamicWithArray
{
    private int[] id;
    private int[] sz;
    private int count;
    //
    public WeightedQuickUnionUFofDynamicWithArray()
    {
        count=2;
        id=new int[2];
        id[0]=0;
        id[1]=1;
        //
        sz=new int[2];
        sz[0]=1;
        sz[1]=1;
        //
    }
   
     public int count()
     {return count;}
    
      boolean connected(int p,int q)
      {
          //is false when p or q is bigger than index of id
          if (p>id.length-1 || q>id.length-1)
              return false;
          else
             return find(p)==find(q);
      }
    
      public int find(int p)
      {
          while(p!=id[p])
          {
              p=id[p];
          }
          return p;
      }
      
    
      public void union(int p,int q)
      {
          if(p>id.length-1 || q>id.length-1)
          {
             // resize array id and sz length to p+1 or q+1, marksure array max index is p or q.  
              if (p>q)
                  resize(p+1);
              else
                 resize(q+1);
          }
          //
          int i=find(p);
          int j=find(q);
          if(i==j) return;
          if(sz[i]<sz[j])
          {
              id[i]=j;
              sz[j]=sz[j]+sz[i];
           }
          else
          {
              id[j]=i;
              sz[i]=sz[i]+sz[j];
          }
          count--;
         }
     
      public int newSite()
      {//with array,this method return the max index of id or sz.
          return id.length;
      }
     
      private void resize(int max)
      {
          int[] tempID=new int[max];
          for(int i=0;i<id.length;i++)
              tempID[i]=id[i];
          for(int j=id.length;j<max;j++)
              tempID[j]=j;
          id=tempID;
          //
          int[] tempSZ=new int[max];
          for(int i=0;i<sz.length;i++)
              tempSZ[i]=sz[i];
          for(int j=sz.length;j<max;j++)
              tempSZ[j]=1;
          sz=tempSZ;
      }
      
       public static void main(String[] qrgs)
       {
           WeightedQuickUnionUFofDynamicWithArray uf=new WeightedQuickUnionUFofDynamicWithArray();
           while (!StdIn.isEmpty())
           {
               int p=StdIn.readInt();
               int q=StdIn.readInt();
               StdOut.printf("p=%d  q=%d ",p,q);
               if(uf.connected(p,q)) continue;
               uf.union(p,q);
            }//end while
        }//end main
}//end class

原文地址:https://www.cnblogs.com/longjin2018/p/9854832.html