• Algs4-1.5-quick-union


    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;
        }
       
         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--;
           }
           */
          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;
                   uf.union(p,q);
                   StdOut.println(p+ " " +q);
                }//end while
            }//end main
    }//end class

  • 相关阅读:
    主要工业以太网性能横向比较
    聊一聊工业以太网
    FPGA学习之RoadMap
    我眼中的FPGA
    板级通信总线之SPI及其Verilog实现
    ALTERA FPGA中实现低于时钟周期的端口延时
    Javascript 闭包浅析(一)
    node.js docker centos7 下环境构建命令
    ruby sass 命令
    如何配置nginx的反向代理nodes 3000端口项目
  • 原文地址:https://www.cnblogs.com/longjin2018/p/9854642.html
Copyright © 2020-2023  润新知