Пример #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);
            }
        }
        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));
            }
        }
        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));
        }