示例#1
0
        // Find, with path halving: avoids recursion

        public Eqclass <T> Find()
        {
            if (link == null)
            {
                return(this);
            }
            else if (link.link == null)
            {
                return(link);
            }
            else
            {
                // Grandparent, parent, and link
                Eqclass <T> pp = this, p = link, plink = p.link;
                while (plink != null)
                {
                    // Invariant: pp -> p -> plink
                    pp.link = plink;
                    pp      = p;
                    p       = plink;
                    plink   = p.link;
                }
                return(p);
            }
        }
示例#2
0
        public static Eqclass <T> Make(T item)
        {
            Eqclass <T> result;

            if (!dict.Find(item, out result))
            {
                dict[item] = result = new Eqclass <T>(item);
            }
            return(result);
        }
示例#3
0
        public static void Main(String[] args)
        {
            Eqclass <int> x = Eqclass <int> .Make(3),
                          y = Eqclass <int> .Make(4),
                          z = Eqclass <int> .Make(5);

            x.Union(y);
            y.Union(z);
            Console.WriteLine(x.Find().Item);
            Console.WriteLine(y.Find().Item);
            Console.WriteLine(z.Find().Item);
        }
示例#4
0
        public void Union(Eqclass <T> that)
        {
            Eqclass <T> thatRep = that.Find(), thisRep = this.Find();

            if (thatRep != thisRep)
            {
                if (thatRep.rank == thisRep.rank)
                {
                    thisRep.link = thatRep;
                    thatRep.rank++;
                }
                else if (thatRep.rank > thisRep.rank)
                {
                    thisRep.link = thatRep;
                }
                else
                {
                    thatRep.link = thisRep;
                }
            }
        }