Algs4-1.5.1使用quick-find算法处理序列

时间:2021-07-04 22:04:26

1.5.1使用quick-find算法处理序列9-0 3-4 5-8 7-2 2-1 5-7 0-3 4-2。对于输入的每一对整数,给出id[]数组的内容和访问数组的次数。
答:
Algs4-1.5.1使用quick-find算法处理序列
Algs4-1.5.1使用quick-find算法处理序列
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--;
      }
       */
       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

文件:tinyUF.txt
10
9
0
3
4
5
8
7
2
2
1
5
7
0
3
4
2

相关文章