Ejemplo n.º 1
0
        public override void Solve(IOManager io)
        {
            var n    = io.ReadInt();
            var tree = new BasicGraph(n);

            for (int i = 0; i < n - 1; i++)
            {
                var u = io.ReadInt();
                var v = io.ReadInt();
                u--;
                v--;
                tree.AddEdge(u, v);
                tree.AddEdge(v, u);
            }

            var lca = new LowestCommonAncester(tree);

            var queries = io.ReadInt();

            for (int q = 0; q < queries; q++)
            {
                var a = io.ReadInt() - 1;
                var b = io.ReadInt() - 1;
                io.WriteLine(lca.Depths[a] + lca.Depths[b] - 2 * lca.Depths[lca.GetLcaNode(a, b)] + 1);
            }
        }
Ejemplo n.º 2
0
        public override void Solve(IOManager io)
        {
            var n    = io.ReadInt();
            var tree = new BasicGraph(n);
            var root = -1;

            for (int i = 0; i < n; i++)
            {
                var p = io.ReadInt();

                if (p == -1)
                {
                    root = i;
                }
                else
                {
                    p--;
                    tree.AddEdge(p, i);
                }
            }

            var lca = new LowestCommonAncester(tree, root);

            var queries = io.ReadInt();

            for (int q = 0; q < queries; q++)
            {
                var staff = io.ReadInt() - 1;
                var boss  = io.ReadInt() - 1;

                if (lca.GetLcaNode(staff, boss) == boss)
                {
                    io.WriteLine("Yes");
                }
                else
                {
                    io.WriteLine("No");
                }
            }
        }