• Algs4-1.5.4给出id[]和sz[]的内容与次数


    1.5.4在正文的加权quick-union算法示例中,对于输入的每一对整数(包括对照输入和最坏情况下的输入),给出id[]和sz[]数组的内容以及访问数组的次数。
    答:
    1)示例:

    图片

    2)对照输入:

    图片

    图片

    3)最坏输入

    图片

    图片

    4)code:
    public class WeightedQuickUnionUF
    {
        private int[] id;
        private int[] sz;
        private int count;
        public WeightedQuickUnionUF(int N)
        {
            count=N;
            id=new int[N];
            for (int i=0;i<N;i++)
             {
                id[i]=i;
                StdOut.printf("%3d",i);
             }
             StdOut.println();
            //
            sz=new int[N];
            for (int i=0;i<N;i++)
                sz[i]=1;
            //
        }
       
         public int count()
         {return count;}
        
          boolean connected(int p,int q)
          {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)
          {
              int i=find(p);
              int j=find(q);
              StdOut.printf(" i=%d j=%d ",i,j);
              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--;
              //
              for (int k=0;k<id.length;k++)
                  StdOut.printf("%3d",id[k]);
              StdOut.printf(" ");
              for (int k=0;k<id.length;k++)
                  StdOut.printf("%3d",sz[k]);
              StdOut.printf(" ");
          }
          
           public static void main(String[] qrgs)
           {
               int N=StdIn.readInt();
               WeightedQuickUnionUF uf=new WeightedQuickUnionUF(N);
               while (!StdIn.isEmpty())
               {
                   int p=StdIn.readInt();
                   int q=StdIn.readInt();
                   if(uf.connected(p,q)) continue;
                    StdOut.printf("p=%d q=%d",p,q);
                   uf.union(p,q);
                }//end while
            }//end main
    }//end class

  • 相关阅读:
    开源.NET FTP组件edtFTPnet 用法
    C#开发的较好的FTP类
    C# 配置文件读取与修改
    对于List的All,Any,Where,FirstOrDefault,Average,Sum,Distinct,Union,AddRange,RemoveRange,InsertRange,GetRange操作
    一次性打印多个C1FlexGrid
    Word自动生成目录页码靠右对齐
    Windows Workflow学习文档
    Windows Workflow开发演练
    Boo who
    Missing letters
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9854688.html
Copyright © 2020-2023  润新知