Пример #1
0
        public RootedTreeNode(RootedTree tree, Node node, int parentIndex, int level)
        {
            Tree         = tree;
            Node         = node;
            Level        = level;
            _parentIndex = parentIndex;

            var children = new List <RootedTreeNode>(node.Degree);

            foreach (Node child in Node.GetAdjacentNodes().Where(x => x.Index != parentIndex))
            {
                children.Add(tree.GetNode(child.Index));
            }
            Children = children.ToArray();

            tree.SetNode(this);
        }
Пример #2
0
        public void TestTreeLCA()
        {
            Random r = new Random(0);

            for (int i = 0; i < 10; i++)
            {
                int   N    = r.Next(30000, 40000);
                int[] perm = new int[N];
                for (int j = 0; j < N; j++)
                {
                    perm[j] = j;
                }
                for (int j = 0; j < N; j++)
                {
                    int swap = j + r.Next(N - j);
                    int tmp  = perm[j];
                    perm[j]    = perm[swap];
                    perm[swap] = tmp;
                }

                Graph g = new Graph(N);
                for (int j = 1; j < N; j++)
                {
                    int a = r.Next(j);
                    g.AddEdge(perm[a], perm[j]);
                }
                RootedTree tree = new RootedTree(g, g.GetNode(perm[0]));

                for (int j = 0; j < 100; j++)
                {
                    int            a = r.Next(N), b = r.Next(N);
                    RootedTreeNode p = tree.GetNode(a), q = tree.GetNode(b);

                    // Naive solution
                    var pp = p;
                    var qq = q;
                    List <RootedTreeNode> ptrail = new List <RootedTreeNode>(), qtrail = new List <RootedTreeNode>();
                    while (pp != null)
                    {
                        ptrail.Add(pp);
                        pp = pp.Parent;
                    }
                    while (qq != null)
                    {
                        qtrail.Add(qq);
                        qq = qq.Parent;
                    }
                    ptrail.Reverse();
                    qtrail.Reverse();
                    int k = 0;
                    while (k + 1 < ptrail.Count && k + 1 < qtrail.Count && ptrail[k + 1] == qtrail[k + 1])
                    {
                        k++;
                    }
                    RootedTreeNode expected = ptrail[k];

                    RootedTreeNode lca = tree.GetLowestCommonAncestor(p, q);

                    Assert.AreSame(expected, lca);
                }
            }
        }