Пример #1
0
        public static void Solve()
        {
            var N = Scanner.Scan <int>();
            var G = new List <int> [N].Select(x => new List <int>()).ToArray();

            for (var i = 0; i < N - 1; i++)
            {
                var(x, y) = Scanner.Scan <int, int>();
                x--;
                y--;
                G[x].Add(y);
                G[y].Add(x);
            }

            var lca = new LowestCommonAncestor(G);
            var Q   = Scanner.Scan <int>();

            for (var i = 0; i < Q; i++)
            {
                var(a, b) = Scanner.Scan <int, int>();
                a--;
                b--;
                var answer = lca.GetDistance(a, b) + 1;
                Console.WriteLine(answer);
            }
        }
Пример #2
0
        static void Main(string[] args)
        {
            Console.WriteLine("Hello World!");
            TreeTraversal.Run();
            CheckIfBinaryTreeBST.Run();
            BinaryTreeOperations.Run();
            TransformToBST.Run();
            LowestCommonAncestor.Run();
            BSTOperations.Run();

            Console.WriteLine();
            GraphTraversal graph = new GraphTraversal();

            graph.Run();

            Console.WriteLine();
            Console.WriteLine("Dijkstra Algo:");
            Dijkstra dj = new Dijkstra();

            dj.Run();

            SortingAlogrithm.Run();
            Console.WriteLine();
            Console.WriteLine("Heap : ");
            HeapProblem.Run();
            Console.ReadLine();
        }
Пример #3
0
    public void Solve()
    {
        int N = Reader.Int(), M = Reader.Int();
        var E    = Reader.IntTable(M);
        int NQ   = Reader.Int();
        var Q    = Reader.IntTable(NQ);
        var comp = new TwoEdgeConnectedComponent(N, E, 1);
        var lca  = new LowestCommonAncestor(comp.Components.Count);

        for (int a = 0; a < comp.Components.Count; a++)
        {
            foreach (int b in comp.Components[a].Edges)
            {
                if (a < b)
                {
                    lca.AddEdge(a, b);
                }
            }
        }
        lca.Init(0);
        var ans = new bool[NQ];

        for (int i = 0; i < NQ; i++)
        {
            int a = comp.VtoComponentId(Q[i][0] - 1);
            int b = comp.VtoComponentId(Q[i][1] - 1);
            int c = comp.VtoComponentId(Q[i][2] - 1);
            ans[i] = a == b && a == c || lca.Dist(a, b) + lca.Dist(b, c) == lca.Dist(a, c);
        }
        Console.WriteLine(string.Join("\n", ans.Select(b => b ? "OK" : "NG")));
    }
Пример #4
0
        public void TestGetLowestCommonAncestor()
        {
            BinaryTree testTree = LowestCommonAncestor.GenerateTestTree();

            //                     __[1]__
            //                    /       \
            //                   /         \
            //                [2]           [9]
            //               /   \             \
            //            [3]     [8]           [10]
            //           /   \                 /    \
            //        [4]     [6]          [11]      [12]
            //           \       \        /    \         \
            //            [5]     [7] [13]      [14]      [16]
            //                                 /         /
            //                             [15]      [17]

            Assert.AreEqual(testTree.GetLowestCommonAncestor(1, 1).GetVal(),
                            1,
                            "Lowest common ancestor of the same nodes should be that node");

            Assert.AreEqual(testTree.GetLowestCommonAncestor(3, 7).GetVal(),
                            3,
                            "Lowest common ancestor of a pair of nodes a b where a is an ancestor of b should be a");

            Assert.AreEqual(testTree.GetLowestCommonAncestor(13, 14).GetVal(),
                            11,
                            "LCA of a pair of arbitrary nodes should return the correct result");

            Assert.AreEqual(testTree.GetLowestCommonAncestor(17, 5).GetVal(),
                            1,
                            "Method should still work if the LCA is the root");
        }
Пример #5
0
        public static void Solve()
        {
            var(N, X) = Scanner.Scan <int, int>();
            var tree = new LowestCommonAncestor(N);

            for (var i = 0; i < N - 1; i++)
            {
                var(a, b, c) = Scanner.Scan <int, int, long>();
                a--; b--;
                tree.AddEdge(a, b, c);
            }

            for (var i = 0; i < N; i++)
            {
                for (var j = 0; j < N; j++)
                {
                    if (tree.GetCost(i, j) == X)
                    {
                        Console.WriteLine("Yes");
                        return;
                    }
                }
            }

            Console.WriteLine("No");
        }
        public void TestLca()
        {
            BinarySearchTree <int> tree = BinarySearchTree <int> .MakeSampleValidTree();

            Assert.AreEqual(6, LowestCommonAncestor <int> .FindLca(tree.Find(3), tree.Find(15)));
            Assert.AreEqual(17, LowestCommonAncestor <int> .FindLca(tree.Find(1), tree.Find(48)));
            Assert.AreEqual(17, LowestCommonAncestor <int> .FindLca(tree.Find(17), tree.Find(48)));
        }
Пример #7
0
    public void Solve()
    {
        int N = Reader.Int(), A = Reader.Int() - 1, B = Reader.Int() - 1;
        var E = new List <int> [2][];

        for (int who = 0; who < 2; who++)
        {
            E[who] = new List <int> [N];
            for (int i = 0; i < N; i++)
            {
                E[who][i] = new List <int>();
            }
            for (int i = 0; i < N - 1; i++)
            {
                int a = Reader.Int() - 1, b = Reader.Int() - 1;
                E[who][a].Add(b);
                E[who][b].Add(a);
            }
        }
        var lca  = new LowestCommonAncestor(B, E[1]);
        var seen = new bool[N];
        var que  = new Queue <int>();

        que.Enqueue(A);
        int ans = lca.Depth(A) * 2;

        for (int steps = 1; que.Count > 0; steps++)
        {
            var nextQue = new Queue <int>();
            while (que.Count > 0)
            {
                int at = que.Dequeue();
                foreach (int next in E[0][at])
                {
                    if (!seen[next])
                    {
                        if (lca.Dist(at, next) > 2)
                        {
                            Console.WriteLine(-1); return;
                        }
                        seen[next] = true;
                        int nextDepth = lca.Depth(next);
                        if (nextDepth >= steps)
                        {
                            ans = Math.Max(ans, nextDepth * 2);
                        }
                        if (nextDepth > steps)
                        {
                            nextQue.Enqueue(next);
                        }
                    }
                }
            }
            que = nextQue;
        }

        Console.WriteLine(ans);
    }
 public void InitializeTest()
 {
     Assert.Throws <ArgumentOutOfRangeException>(() => _ = new LowestCommonAncestor(0));
     Assert.Throws <ArgumentOutOfRangeException>(() => _ = new LowestCommonAncestor(1, -1));
     Assert.Throws <ArgumentOutOfRangeException>(() => _ = new LowestCommonAncestor(1, 1));
     Assert.DoesNotThrow(() => _ = new LowestCommonAncestor(1));
     Assert.DoesNotThrow(() => _ = new LowestCommonAncestor(2, 1));
     Assert.That(new LowestCommonAncestor(1).Length, Is.EqualTo(1));
 }
        void InternalTest(int?[] tree, int p, int q, TreeNode expected)
        {
            TreeNode root   = TreeNode.Get(tree);
            TreeNode nodeP  = new TreeNode(p);
            TreeNode nodeQ  = new TreeNode(q);
            TreeNode actual = LowestCommonAncestor.Solve(root, nodeP, nodeQ);

            Assert.Equal <int>(expected.val, actual.val);
        }
Пример #10
0
        public IActionResult lcaFind(LowestCommonAncestor lowestCommonAncestor)
        {
            var lcaValue = arbolRepo.LowestCommonAncestor(lowestCommonAncestor);

            if (lcaValue == 0)
            {
                return(BadRequest());
            }
            return(Ok(lcaValue));
        }
Пример #11
0
        public void FindsALowerCommonAncestor()
        {
            var inputOne = TreeNode.BuildTreeOne();
            var lcaOne   = LowestCommonAncestor.Get(inputOne, 1, 6);

            Assert.Equal(5, lcaOne.Value);

            var inputTwo = TreeNode.BuildTreeTwo();
            var lcaTwo   = LowestCommonAncestor.Get(inputTwo, 5, 7);

            Assert.Equal(6, lcaTwo.Value);
        }
Пример #12
0
        public void ShouldFind_LCA_AtRoot()
        {
            var nodes = new int?[] { 6, 2, 8, 0, 4, 7, 9, null, null, 3, 5 };
            var tree  = new TreeNode(nodes);

            var p = new TreeNode(2);
            var q = new TreeNode(8);

            var lca = LowestCommonAncestor.FindLowestCommonAncestor(tree, p, q);

            Assert.AreEqual(6, lca.val);
        }
Пример #13
0
        public void ShouldFind_LCA_AtLeft_FirstAndSecondLevel()
        {
            var nodes = new int?[] { 6, 2, 8, 0, 4, 7, 9, null, null, 3, 5 };
            var tree  = new TreeNode(nodes);

            var p = new TreeNode(0);
            var q = new TreeNode(5);

            var lca = LowestCommonAncestor.FindLowestCommonAncestor(tree, p, q);

            Assert.AreEqual(2, lca.val);
        }
Пример #14
0
        public void ReturnsLowestCommonAncestorForInherittedNodes()
        {
            var inputOne = TreeNode.BuildTreeOne();
            var lcaOne   = LowestCommonAncestor.Get(inputOne, 7, 6);

            Assert.Equal(7, lcaOne.Value);

            var inputTwo = TreeNode.BuildTreeTwo();
            var lcaTwo   = LowestCommonAncestor.Get(inputTwo, 5, 3);

            Assert.Equal(3, lcaTwo.Value);
        }
        private static LowestCommonAncestor InitializeLca(int root = 0)
        {
            var lca = new LowestCommonAncestor(6, root);

            lca.AddEdge(0, 1);
            lca.AddEdge(0, 2);
            lca.AddEdge(1, 3);
            lca.AddEdge(1, 4);
            lca.AddEdge(2, 5);

            return(lca);
        }
Пример #16
0
 static void Main(string[] args)
 {
     //SolutionInorderTraversal.Run();
     //SolutionPreorderTraversal.Run();
     //SolutionPostorderTraversal.Run();
     //SolutionLevelOrderTraversal.Run();
     //MaxDepthOfBTree.Run();
     //SymmetricTree.Run();
     //PathSum.Run();
     //ReconstructFromInorderAndPostorder.Run();
     //PopulatingNextRightPointers.Run();
     LowestCommonAncestor.Run();
 }
Пример #17
0
        public int LowestCommonAncestor(LowestCommonAncestor lowestCommonAncestor)
        {
            CrearArbol arbol = new CrearArbol()
            {
                nodeValues = lowestCommonAncestor.nodeValues
            };
            Nodo nodoRaiz = arbolaBuscar(arbol);
            Nodo lcaValue = FindLca(nodoRaiz, lowestCommonAncestor.valueOne, lowestCommonAncestor.valueTwo);

            if (lcaValue == null)
            {
                return(0);
            }
            return(lcaValue.nodeValue);
        }
        public void ArgumentOutOfRangeInMethodTest(int u, int v)
        {
            const int length = 6;
            var       sut    = new LowestCommonAncestor(length);

            Assert.Throws <ArgumentOutOfRangeException>(() => sut.AddEdge(u, v));
            Assert.Throws <ArgumentOutOfRangeException>(() => _ = sut.Find(u, v));
            Assert.Throws <ArgumentOutOfRangeException>(() => _ = sut.GetDistance(u, v));
            Assert.Throws <ArgumentOutOfRangeException>(() => _ = sut.GetCost(u, v));
            Assert.Throws <ArgumentOutOfRangeException>(() => _ = sut.GetCost(u, v, 7));
            if (v < 0 || length <= v)
            {
                return;
            }
            Assert.Throws <ArgumentOutOfRangeException>(() => _ = sut.GetAncestor(u, 0));
        }
Пример #19
0
    public void Solve()
    {
        int N   = Reader.Int();
        var E   = Reader.IntTable(N - 1);
        int NQ  = Reader.Int();
        var Q   = Reader.IntTable(NQ);
        var g   = new LowestCommonAncestor(N, E, 0, 1);
        var ans = new StringBuilder();

        foreach (var q in Q)
        {
            int a = q[0] - 1, b = q[1] - 1;
            int len = 1 + g.Dist(a, b);
            ans.Append(len + "\n");
        }
        Console.Write(ans);
    }
        public void GetCostTest(int u, int v, int c)
        {
            const int n = 6;
            const int m = 7;

            for (var i = 0; i < n; i++)
            {
                var sut = new LowestCommonAncestor(n, i);
                sut.AddEdge(0, 1, 1);
                sut.AddEdge(0, 2, 3);
                sut.AddEdge(2, 3, 5);
                sut.AddEdge(2, 4, 2);
                sut.AddEdge(3, 5, 7);

                Assert.That(sut.GetCost(u, v), Is.EqualTo(c));
                Assert.That(sut.GetCost(u, v, m), Is.EqualTo(c % m));
                Assert.That(sut.GetCost(v, u), Is.EqualTo(c));
            }
        }
Пример #21
0
        public void TestInsertInBinaryTree()
        {
            BinaryTree testTree = new BinaryTree(null);

            testTree.Insert(5);
            Assert.AreEqual(testTree.GetRoot().GetVal(),
                            5,
                            "A value inserted into a binary tree with no root should become the root");

            testTree.Insert(6);
            Assert.AreEqual(testTree.GetRoot().GetLChild().GetVal(),
                            6,
                            "Insertion for a node with no children should make it the lchild");

            testTree.Insert(7);
            Assert.AreEqual(testTree.GetRoot().GetRChild().GetVal(),
                            7,
                            "Insertion for a node with an lchild should make the new value the rchild");

            testTree.Insert(8);
            Assert.AreEqual(testTree.GetRoot().GetLChild().GetLChild().GetVal(),
                            8,
                            "Insertion to a tree that has a full bottom row should see the value inserted in the leftmost position on the next row");

            //                     __[1]__
            //                    /       \
            //                   /         \
            //                [2]           [9]
            //               /   \             \
            //            [3]     [8]           [10]
            //           /   \                 /    \
            //        [4]     [6]          [11]      [12]
            //           \       \        /    \         \
            //            [5]     [7] [13]      [14]      [16]
            //                                 /         /
            //                             [15]      [17]
            testTree = LowestCommonAncestor.GenerateTestTree();
            testTree.Insert(18);

            Assert.AreEqual(testTree.GetRoot().GetRChild().GetLChild().GetVal(),
                            18,
                            "Insertion into a binary tree with random shape should go to the correct spot");
        }
        public void GetDistanceAndCostTest(int u, int v, int c)
        {
            const int n = 6;

            for (var i = 0; i < n; i++)
            {
                var sut = new LowestCommonAncestor(6, i);
                sut.AddEdge(0, 1);
                sut.AddEdge(0, 2);
                sut.AddEdge(1, 3);
                sut.AddEdge(1, 4);
                sut.AddEdge(2, 5);

                Assert.That(sut.GetDistance(u, v), Is.EqualTo(c));
                Assert.That(sut.GetDistance(v, u), Is.EqualTo(c));
                Assert.That(sut.GetCost(u, v), Is.EqualTo(c));
                Assert.That(sut.GetCost(v, u), Is.EqualTo(c));
            }
        }
            protected (bool AnalysisSucceded, bool VarAlwaysAssigned) CheckCandidate(StatementSyntax assignmentStatement)
            {
                var lcaResult        = LowestCommonAncestor.GetCommonAncestorForSyntaxStatements(assignmentStatement, InvocationStatement);
                var scopedAssignment = lcaResult.ScopedX;
                var scopedInvocation = lcaResult.ScopedY;

                if (scopedAssignment == null || scopedInvocation == null)
                {
                    return(false, false);                            //If there was some kind of error during analysis we should assume the worst case - that the candidat is valid but not always assigns variable
                }
                switch (scopedAssignment)
                {
                case SwitchStatementSyntax _:
                case IfStatementSyntax _:
                    return(true, false);
                }

                DataFlowAnalysis flowAnalysisWithAssignment = null;

                try
                {
                    flowAnalysisWithAssignment = SemanticModel.AnalyzeDataFlow(scopedAssignment, scopedInvocation);
                }
                catch
                {
                    return(false, false);
                }

                if (flowAnalysisWithAssignment == null || !flowAnalysisWithAssignment.Succeeded)
                {
                    return(false, false);
                }
                if (flowAnalysisWithAssignment.AlwaysAssigned.All(var => var.Name != VariableName))
                {
                    return(true, false);
                }

                return(true, true);
            }
Пример #24
0
        public static void Solve()
        {
            var N   = Scanner.Scan <int>();
            var lca = new LowestCommonAncestor(N + 1);

            for (var i = 1; i <= N; i++)
            {
                var p = Scanner.Scan <int>();
                if (p == -1)
                {
                    p = 0;
                }
                lca.AddEdge(p, i);
            }

            var Q = Scanner.Scan <int>();

            while (Q-- > 0)
            {
                var(a, b) = Scanner.Scan <int, int>();
                var p = lca.Find(a, b);
                Console.WriteLine(p == b ? "Yes" : "No");
            }
        }
Пример #25
0
    public void Solve()
    {
        int N = NextInt(), M = NextInt();
        var E = new int[M][];

        for (int i = 0; i < M; i++)
        {
            E[i] = new[] { NextInt(), NextInt() }
        }
        ;
        int NQ = NextInt();
        var Q  = new int[NQ][];

        for (int i = 0; i < NQ; i++)
        {
            Q[i] = new[] { NextInt(), NextInt(), NextInt() }
        }
        ;
        var comp = new TwoEdgeConnectedComponent(N, E, 1);
        var lca  = new LowestCommonAncestor(comp.Components.Count);

        for (int a = 0; a < comp.Components.Count; a++)
        {
            foreach (int b in comp.Components[a].Edges)
            {
                if (a < b)
                {
                    lca.AddEdge(a, b);
                }
            }
        }
        lca.Init(0);
        var ans = new bool[NQ];

        for (int i = 0; i < NQ; i++)
        {
            int a = comp.VtoComponentId(Q[i][0] - 1);
            int b = comp.VtoComponentId(Q[i][1] - 1);
            int c = comp.VtoComponentId(Q[i][2] - 1);
            ans[i] = a == b && a == c || lca.Dist(a, b) + lca.Dist(b, c) == lca.Dist(a, c);
        }
        Console.WriteLine(string.Join("\n", ans.Select(b => b ? "OK" : "NG")));
    }

    TextReader _reader = Console.In;
    int NextInt()
    {
        int c;

        while ((c = _reader.Read()) < '0' || c > '9')
        {
        }
        int res = c - '0';

        while ((c = _reader.Read()) >= '0' && c <= '9')
        {
            res = res * 10 + c - '0';
        }
        return(res);
    }
}