Algs4-1.5.2使用quick-union算法完成练习1.5.1

1.5.2使用quick-union算法(请见1.5.2.3节代码框)完成练习1.5.1。另外,在处理完输入的每对整数之后画出id[]数组表示的森林。
答:

图片

图片

图片

图片
public class UF
{
    private int[] id;
    private int count;
    public UF(int N)
    {
        count=N;
        id=new int[N];
        for (int i=0;i<N;i++)
        {
            id[i]=i;
          StdOut.printf("%3d",i);
        }
        StdOut.println();
    }
   
     public int count()
     {return count;}
    
      boolean connected(int p,int q)
      {return find(p)==find(q);}
     /*quick-find
       public int find(int p)
       {return id[p];}
      
       public  void union(int p,int q)
       {
          int pID=find(p);
          int qID=find(q);
          if (pID==qID) return;
          for (int i=0;i<id.length;i++)
              if(id[i]==pID) id[i]=qID;
          count--;
          for (int i=0;i<id.length;i++)
              StdOut.printf("%3d",id[i]);
          StdOut.println();
       }
      */

      public int find(int p)
      {
          while(p!=id[p]) p=id[p];
          return p;
      }
     
      public void union(int p,int q)
      {
          int pRoot=find(p);
          int qRoot=find(q);
          if(pRoot==qRoot) return;
          id[pRoot]=qRoot;
          count--;
          //
           for (int i=0;i<id.length;i++)
              StdOut.printf("%3d",id[i]);
          StdOut.println();
      }

       public static void main(String[] qrgs)
       {
           int N=StdIn.readInt();
           UF uf=new UF(N);
           while (!StdIn.isEmpty())
           {
               int p=StdIn.readInt();
               int q=StdIn.readInt();
               if(uf.connected(p,q)) continue;
               StdOut.println(p+ " " +q);
               uf.union(p,q);
              
            }//end while
        }//end main
}//end class

posted @ 2018-10-26 09:55  修电脑的龙生  阅读(488)  评论(0编辑  收藏  举报