Problem:
Score : 600 points

Problem Statement

We have a tree with N vertices. The i-th edge connects Vertex A_i and B_i bidirectionally.

Takahashi is standing at Vertex u, and Aoki is standing at Vertex v.

Now, they will play a game of tag as follows:

1. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Takahashi moves to a vertex of his choice that is adjacent to his current vertex.

2. If Takahashi and Aoki are standing at the same vertex, the game ends. Otherwise, Aoki moves to a vertex of his choice that is adjacent to his current vertex.

3. Go back to step 1.

Takahashi performs his moves so that the game ends as late as possible, while Aoki performs his moves so that the game ends as early as possible.

Find the number of moves Aoki will perform before the end of the game if both Takahashi and Aoki know each other's position and strategy.

It can be proved that the game is bound to end.

Constraints

2 \leq N \leq 10^5

1 \leq u,v \leq N

u \neq v

1 \leq A_i,B_i \leq N

The given graph is a tree.

Input

Input is given from Standard Input in the following format:

N u v
A_1 B_1
:
A_{N-1} B_{N-1}

Output

Print the number of moves Aoki will perform before the end of the game.

Sample Input 1

5 4 1
1 2
2 3
3 4
3 5

Sample Output 1

2

If both players play optimally, the game will progress as follows:

Takahashi moves to Vertex 3.

Aoki moves to Vertex 2.

Takahashi moves to Vertex 5.

Aoki moves to Vertex 3.

Takahashi moves to Vertex 3.

Here, Aoki performs two moves.

Note that, in each move, it is prohibited to stay at the current vertex.

Sample Input 2

5 4 5
1 2
1 3
1 4
1 5

Sample Output 2

1

Sample Input 3

2 1 2
1 2

Sample Output 3

0

Sample Input 4

9 6 1
1 2
2 3
3 4
4 5
5 6
4 7
7 8
8 9

Sample Output 4

5

Solution in C# (Mono 4.6.2.0) (judge verdict: Wrong Answer)

// ReSharper disable ArrangeTypeMemberModifiers
// ReSharper disable ConvertIfStatementToSwitchStatement
// ReSharper disable FunctionRecursiveOnAllPaths
// ReSharper disable InconsistentNaming
// ReSharper disable InlineOutVariableDeclaration
// ReSharper disable InvertIf
// ReSharper disable JoinDeclarationAndInitializer
// ReSharper disable MemberCanBeMadeStatic.Global
// ReSharper disable MemberCanBeMadeStatic.Local
// ReSharper disable NonReadonlyMemberInGetHashCode
// ReSharper disable PossibleNullReferenceException
// ReSharper disable RedundantUsingDirective
// ReSharper disable SuggestVarOrType_BuiltInTypes
// ReSharper disable SuggestVarOrType_Elsewhere
// ReSharper disable TailRecursiveCall
// ReSharper disable UnusedMember.Global
// ReSharper disable UnusedMember.Local
// ReSharper disable UseObjectOrCollectionInitializert

#if true && UTAKA_LOCAL

//#if false
#define UTAKA_DEBUG
#endif

//#define TOPCODER

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Numerics;
using System.Runtime.InteropServices;
using System.Security.Cryptography;
using static UtakaApp.Util;

namespace UtakaApp
{
    public partial class Program
    {
        public const string SiteName    = "AtCoder";
        public const string ContestName = "abc148";
        public const string ProblemName = "F";

        public static int u;
        public static int v;

        public void Solve()
        {
            int N = cin.ReadInt;
            u = cin.ReadInt - 1;
            v = cin.ReadInt - 1;

            LowestCommonAncestor lca = new LowestCommonAncestor(N);


            int[] A = new int[N - 1];
            int[] B = new int[N - 1];

            for (int i = 0; i < N - 1; i++)
            {
                A[i] = cin.ReadInt - 1;
                B[i] = cin.ReadInt - 1;

                lca.AddEdge(A[i], B[i]);
            }

            // 青木くんがroot
            lca.Build(root: v);

            int dist = lca.GetDistance(u, v);

            int dist2 = dist / 2;

            // if (dist2 == 0)
            // {
            //     Dbg.WriteLine("!!!!!!!!!!!!!dist == 0");
            //     cou.WriteLine(dist);
            //     return;
            // }

            if (u == v)
            {
                cou.WriteLine(0);
                return;
            }

            if (dist == 1)
            {
                if (lca.G[u].Count == 1)
                {
                    // Dbg.WriteLine("!!!!!!!!!!!!逃げ場なし");
                    cou.WriteLine(0);
                    return;
                }
            }

            if (dist == 2)
            {
                if (lca.G[u].Count == 1)
                {
                    cou.WriteLine(1);
                    return;
                }
            }

            int ind1 = lca.pathIndexes[dist2 - 1];
            int ind2 = lca.pathIndexes[dist2];


            var lca2 = new LowestCommonAncestor(N);

            for (int i = 0; i < N - 1; i++)
            {
                if ((A[i] == ind1 && B[i] == ind2) || (A[i] == ind2 && B[i] == ind1))
                {
                    continue;
                }

                lca2.AddEdge(A[i], B[i]);
            }

            lca2.Build(root: ind2);

            int ans = lca2.depth.Max();

            ans += dist2;

            ans--;

            cou.WriteLine(ans);
        }
    }


    /// <summary>
    /// 最小共通祖先を求める
    /// </summary>
    public class LowestCommonAncestor
    {
        public int N;

        public List<int>[] G;

        public int[] vs;    // オイラーツアーの配列 長さは 2 * N - 1
        public int[] depth; // オイラーツアーの配列のノードの深さ 長さは 2 * N - 1

        public int[] id;               // 最初にそのノードを訪れたときにvs[]にメモしたインデックス 長さは N
        public int[] depthByInitIndex; // もともとのノード配列のインデックスから深さを求めるための配列 長さは N

        public SegTreeForLca segTreeForLca;

        public int[] pathIndexes;
        public bool  found;

        public LowestCommonAncestor(int N)
        {
            this.N = N;

            G = new List<int>[N];

            for (int i = 0; i < N; i++)
            {
                G[i] = new List<int>();
            }

            pathIndexes = new int[N];
            for (int i = 0; i < N; i++)
            {
                pathIndexes[i] = -1;
            }
        }

        public void AddEdge(int a, int b)
        {
            G[a].Add(b);
            G[b].Add(a);
        }

        public void Build(int root)
        {
            vs    = new int[2 * N - 1];
            depth = new int[2 * N - 1];
            id    = new int[N];

            int k = 0;

            Dfs(root, -1, 0, ref k);

            segTreeForLca = new SegTreeForLca(depth);

            depthByInitIndex = new int[N];
            for (int i = 0; i < 2 * N - 1; i++)
            {
                depthByInitIndex[vs[i]] = depth[i];
            }
        }

        /// <summary>
        /// ノードuとノードvの最小共通祖先のノードのインデックスを得る
        /// ここでいうインデックスは、元の配列のインデックスであり、オイラーツアーの方ではないので注意
        /// </summary>
        public int GetLcaIndex(int u, int v)
        {
            int left  = Math.Min(id[u], id[v]);
            int right = Math.Max(id[u], id[v]);

            int eulerIndex = segTreeForLca.QueryWithIndex(left, right + 1).Index;

            return vs[eulerIndex];
        }

        /// <summary>
        /// ノードuとノードvの距離を求める
        /// </summary>
        public int GetDistance(int u, int v)
        {
            int lcaIndex = GetLcaIndex(u, v);
            return depthByInitIndex[u] + depthByInitIndex[v] - 2 * depthByInitIndex[lcaIndex];
        }

        public void Dfs(int v, int parent, int d, ref int k)
        {
            if (!found)
            {
                pathIndexes[d] = v;

                if (v == Program.u)
                {
                    found = true;
                }
            }

            id[v]      = k;
            vs[k]      = v;
            depth[k++] = d;

            for (int i = 0; i < G[v].Count; i++)
            {
                if (G[v][i] != parent)
                {
                    Dfs(G[v][i], v, d + 1, ref k);
                    vs[k]      = v;
                    depth[k++] = d;

                    if (!found)
                    {
                        pathIndexes[d] = v;
                    }
                }
            }
        }
    }

    /// <summary>
    /// 
    /// SegmentTree LCA用
    /// QueryでIndexを取得できるタイプ
    /// 
    /// Dataは0始まりになっている
    /// ノードiの子ノードの番号は 2 * i + 1 / 2 * i + 2
    /// ノードiの親ノードの番号は (i - 1) / 2
    /// 
    ///        0
    ///    1       2
    ///  3   4   5   6
    /// 
    /// </summary>
    public class SegTreeForLca
    {
        private int   leafCount; // 葉の数
        private int[] data;

        private const int identity = int.MaxValue; // 単位元

        private int[] leafIndexes; // そのノードが採用している値の葉のindex

        public SegTreeForLca(IList<int> initialValues)
        {
            int initialValuesLength = initialValues.Count;

            leafCount = 1;

            while (leafCount < initialValuesLength) leafCount <<= 1;

            data        = new int[2 * leafCount - 1];
            leafIndexes = new int[2 * leafCount - 1];

            for (int i = 0; i < initialValuesLength; i++)
            {
                data[i + leafCount - 1]        = initialValues[i];
                leafIndexes[i + leafCount - 1] = i;
            }

            for (int i = initialValuesLength; i < leafCount; i++)
            {
                data[i + leafCount - 1]        = identity;
                leafIndexes[i + leafCount - 1] = i;
            }

            for (int i = leafCount - 2; i >= 0; i--)
            {
                if (data[i * 2 + 1] < data[i * 2 + 2])
                {
                    data[i]        = data[i * 2 + 1];
                    leafIndexes[i] = leafIndexes[i * 2 + 1];
                }
                else
                {
                    data[i]        = data[i * 2 + 2];
                    leafIndexes[i] = leafIndexes[i * 2 + 2];
                }
            }
        }

        /// <summary>
        /// ツリーの更新なしに i番目の葉の値を更新する
        /// </summary>
        public void AssignWithoutUpdate(int i, int value)
        {
            data[i + leafCount - 1] = value;
        }

        /// <summary>
        /// i番目の葉の値を更新し、ツリーを更新する
        /// </summary>
        public void Update(int i, int value)
        {
            int now = i + leafCount - 1;
            data[now] = value;

            while (now > 0)
            {
                now = (now - 1) / 2;

                if (data[now * 2 + 1] < data[now * 2 + 2])
                {
                    data[now]        = data[now * 2 + 1];
                    leafIndexes[now] = leafIndexes[now * 2 + 1];
                }
                else
                {
                    data[now]        = data[now * 2 + 2];
                    leafIndexes[now] = leafIndexes[now * 2 + 2];
                }
            }
        }

        /// <summary>
        /// i番目の葉の値を取得する
        /// </summary>
        public int Look(int i)
        {
            return data[i + leafCount - 1];
        }

        // QueryでIndexを取得したいときに使う
        public struct SegNodePair
        {
            public int Data;
            public int Index;

            public SegNodePair(int data, int index)
            {
                Data  = data;
                Index = index;
            }
        }

        public SegNodePair QueryWithIndex(int a, int b)
        {
            return QueryWithIndexInternal(a, b, 0, 0, leafCount);
        }

        /// <summary>
        /// [a, b) の区間に対するクエリについて
        /// ノード i (区間 [l, r) 担当) が答える
        /// </summary>
        private SegNodePair QueryWithIndexInternal(int a, int b, int i, int l, int r)
        {
            if (r <= a || b <= l) return new SegNodePair(identity, -1);
            if (a <= l && r <= b) return new SegNodePair(data[i], leafIndexes[i]);

            SegNodePair leftPair = QueryWithIndexInternal(a, b, i * 2 + 1,
                l, (l + r) / 2);
            SegNodePair rightPair = QueryWithIndexInternal(a, b, i * 2 + 2,
                (l + r) / 2, r);

            if (leftPair.Data < rightPair.Data)
            {
                return leftPair;
            }
            else
            {
                return rightPair;
            }
        }
    }

//=========================================================================================
// Debug IO
//=========================================================================================

    public partial class Program
    {
        //=========================================================================================
        // Main
        //=========================================================================================

        private readonly ConsoleInput cin;
        private readonly IConsole     cou;

        public Program(ConsoleInput cin, IConsole cou)
        {
            this.cin = cin;
            this.cou = cou;
        }

#if !TOPCODER
        public static void Main(string[] args)
        {
#if UTAKA_LOCAL
//#if false
            new TestCaseCheckerForAtCoder().TestProblems();
#else
            var cin = new ConsoleInput(System.Console.In);
            var console = new MyConsole();
            new Program(cin, console).Solve();
            console.Flush();
#endif
        }
#endif

        public void WriteEnumerable<T>(IEnumerable<T> A, string delimiter = " ")
        {
            if (!A.Any())
            {
                return;
            }

            var sb = new StringBuilder();
            foreach (T v in A)
            {
                sb.Append(v);
                sb.Append(delimiter);
            }

            if (sb.Length > 0)
            {
                sb.Length--;
            }

            cou.WriteLine(sb.ToString());
        }
    }

    public static class Util
    {
        public static int LowerBound<T>(T[] arr, int start, int end, T value, IComparer<T> comparer)
        {
            int low  = start;
            int high = end;
            while (low < high)
            {
                var mid = ((high - low) >> 1) + low;
                if (comparer.Compare(arr[mid], value) < 0)
                    low = mid + 1;
                else
                    high = mid;
            }

            return low;
        }

        public static int LowerBound<T>(T[] arr, T value) where T : IComparable
        {
            return LowerBound(arr, 0, arr.Length, value, Comparer<T>.Default);
        }

        public static int UpperBound<T>(T[] arr, int start, int end, T value, IComparer<T> comparer)
        {
            int low  = start;
            int high = end;
            while (low < high)
            {
                var mid = ((high - low) >> 1) + low;
                if (comparer.Compare(arr[mid], value) <= 0)
                    low = mid + 1;
                else
                    high = mid;
            }

            return low;
        }

        public static int UpperBound<T>(T[] arr, T value)
        {
            return UpperBound(arr, 0, arr.Length, value, Comparer<T>.Default);
        }

        public static int UpperBound<T>(List<T> list, int start, int end, T value, IComparer<T> comparer)
        {
            int low  = start;
            int high = end;
            while (low < high)
            {
                var mid = ((high - low) >> 1) + low;
                if (comparer.Compare(list[mid], value) <= 0)
                    low = mid + 1;
                else
                    high = mid;
            }

            return low;
        }

        public static int UpperBound<T>(List<T> list, T value)
        {
            return UpperBound(list, 0, list.Count, value, Comparer<T>.Default);
        }

        public static T[] Array1D<T>(int a, T defaultValue)
            where T : struct
        {
            var ret = new T[a];
            for (int i = 0; i < a; i++)
            {
                ret[i] = defaultValue;
            }

            return ret;
        }

        public static T[] Array1D<T>(int a)
            where T : struct
        {
            var ret = new T[a];
            return ret;
        }

        /// <summary>
        /// 要素数 (a, b) の、defaultValue で満たされた配列を作成します。
        /// </summary>
        /// <typeparam name="T">配列の型</typeparam>
        /// <param name="a">1次元の要素数</param>
        /// <param name="b">2次元の要素数</param>
        /// <param name="defaultValue">デフォルト値</param>
        /// <returns>指定した条件で初期化された配列</returns>
        public static T[,] Array2D<T>(int a, int b, T defaultValue)
            where T : struct
        {
            var ret = new T[a, b];
            for (int i = 0; i < a; i++)
            {
                for (int j = 0; j < b; j++)
                {
                    ret[i, j] = defaultValue;
                }
            }

            return ret;
        }

        public static T[,,] Array3D<T>(int a, int b, int c, T defaultValue)
            where T : struct
        {
            T[,,] ret = new T[a, b, c];

            for (int i = 0; i < a; i++)
            {
                for (int j = 0; j < b; j++)
                {
                    for (int k = 0; k < c; k++)
                    {
                        ret[i, j, k] = defaultValue;
                    }
                }
            }

            return ret;
        }

        /// <summary>
        /// 要素数 (a, b) の、defaultValue で満たされたJag配列を作成します。
        /// </summary>
        /// <typeparam name="T">配列の型</typeparam>
        /// <param name="a">1次元の要素数</param>
        /// <param name="b">2次元の要素数</param>
        /// <param name="defaultValue">デフォルト値</param>
        /// <returns>指定した条件で初期化された配列</returns>
        public static T[][] JagArray2D<T>(int a, int b, T defaultValue)
            where T : struct
        {
            var ret = new T[a][];
            for (int i = 0; i < a; i++)
            {
                var row = new T[b];
                ret[i] = row;

                for (int j = 0; j < b; j++)
                {
                    row[j] = defaultValue;
                }
            }

            return ret;
        }

        /// <summary>
        /// 要素数 (a, b) のdefault値で満たされたJag配列を作成します。
        /// </summary>
        /// <typeparam name="T">配列の型</typeparam>
        /// <param name="a">1次元の要素数</param>
        /// <param name="b">2次元の要素数</param>
        /// <returns>初期化された配列</returns>
        public static T[][] JagArray2D<T>(int a, int b)
            where T : struct
        {
            var ret = new T[a][];
            for (int i = 0; i < a; i++)
            {
                ret[i] = new T[b];
            }

            return ret;
        }

        public static T[][][] JagArray3D<T>(int a, int b, int c, T defaultValue)
            where T : struct
        {
            var ret = new T[a][][];
            for (int i = 0; i < a; i++)
            {
                T[][] aRow = new T[b][];
                ret[i] = aRow;

                for (int j = 0; j < b; j++)
                {
                    T[] bRow = new T[c];
                    aRow[j] = bRow;

                    for (int k = 0; k < c; k++)
                    {
                        bRow[k] = defaultValue;
                    }
                }
            }

            return ret;
        }

        public static T[][][] JagArray3D<T>(int a, int b, int c)
            where T : struct
        {
            var ret = new T[a][][];
            for (int i = 0; i < a; i++)
            {
                T[][] aRow = new T[b][];
                ret[i] = aRow;

                for (int j = 0; j < b; j++)
                {
                    T[] bRow = new T[c];
                    aRow[j] = bRow;
                }
            }

            return ret;
        }

        public static T[][][][] JagArray4D<T>(int a, int b, int c, int d, T defaultValue)
            where T : struct
        {
            var ret = new T[a][][][];
            for (int i = 0; i < a; i++)
            {
                T[][][] aRow = new T[b][][];
                ret[i] = aRow;

                for (int j = 0; j < b; j++)
                {
                    T[][] bRow = new T[c][];
                    aRow[j] = bRow;

                    for (int k = 0; k < c; k++)
                    {
                        T[] cRow = new T[d];
                        bRow[k] = cRow;

                        for (int l = 0; l < d; l++)
                        {
                            cRow[l] = defaultValue;
                        }
                    }
                }
            }

            return ret;
        }

        public static T[][][][] JagArray4D<T>(int a, int b, int c, int d)
            where T : struct
        {
            var ret = new T[a][][][];
            for (int i = 0; i < a; i++)
            {
                T[][][] aRow = new T[b][][];
                ret[i] = aRow;

                for (int j = 0; j < b; j++)
                {
                    T[][] bRow = new T[c][];
                    aRow[j] = bRow;

                    for (int k = 0; k < c; k++)
                    {
                        T[] cRow = new T[d];
                        bRow[k] = cRow;
                    }
                }
            }

            return ret;
        }

        public static T[][][][][] JagArray5D<T>(int a, int b, int c, int d, int e, T defaultValue)
            where T : struct
        {
            var ret = new T[a][][][][];
            for (int i = 0; i < a; i++)
            {
                T[][][][] aRow = new T[b][][][];
                ret[i] = aRow;

                for (int j = 0; j < b; j++)
                {
                    T[][][] bRow = new T[c][][];
                    aRow[j] = bRow;

                    for (int k = 0; k < c; k++)
                    {
                        T[][] cRow = new T[d][];
                        bRow[k] = cRow;

                        for (int l = 0; l < d; l++)
                        {
                            T[] dRow = new T[e];
                            cRow[l] = dRow;

                            for (int m = 0; m < e; m++)
                            {
                                dRow[m] = defaultValue;
                            }
                        }
                    }
                }
            }

            return ret;
        }

        public static T[][][][][] JagArray5D<T>(int a, int b, int c, int d, int e)
            where T : struct
        {
            var ret = new T[a][][][][];
            for (int i = 0; i < a; i++)
            {
                T[][][][] aRow = new T[b][][][];
                ret[i] = aRow;

                for (int j = 0; j < b; j++)
                {
                    T[][][] bRow = new T[c][][];
                    aRow[j] = bRow;

                    for (int k = 0; k < c; k++)
                    {
                        T[][] cRow = new T[d][];
                        bRow[k] = cRow;

                        for (int l = 0; l < d; l++)
                        {
                            T[] dRow = new T[e];
                            cRow[l] = dRow;
                        }
                    }
                }
            }

            return ret;
        }

        /// <summary>
        /// ジャグ配列をコピーして返す。
        /// </summary>
        public static T[][] CopyJagArray2D<T>(T[][] source)
            where T : struct
        {
            int   len  = source.Length;
            T[][] dest = new T[len][];

            for (int i = 0; i < len; i++)
            {
                T[] inner       = source[i];
                int innerLength = inner.Length;
                T[] newer       = new T[innerLength];
                Array.Copy(inner, newer, innerLength);
                dest[i] = newer;
            }

            return dest;
        }
    }

    public static class UtakaExtentions
    {
        /// <summary>
        /// IList<T>をコピーします
        /// </summary>
        public static T[] Copy<T>(this IList<T> a)
        {
            T[] ret = new T[a.Count];

            for (int i = 0; i < a.Count; i++) ret[i] = a[i];

            return ret;
        }

        /// <summary>
        /// 2次元ジャグ配列をコピーして返す。
        /// </summary>
        public static T[][] Copy<T>(this T[][] source)
            where T : struct
        {
            int   len  = source.Length;
            T[][] dest = new T[len][];

            for (int i = 0; i < len; i++)
            {
                T[] inner       = source[i];
                int innerLength = inner.Length;
                T[] newer       = new T[innerLength];
                Array.Copy(inner, newer, innerLength);
                dest[i] = newer;
            }

            return dest;
        }
    }

    public class IntLargeComparer : IComparer<int>
    {
        public static IntLargeComparer Instance = new IntLargeComparer();

        public int Compare(int x, int y)
        {
            return y - x;
        }
    }

    public class LongLargeComparer : IComparer<long>
    {
        public static LongLargeComparer Instance = new LongLargeComparer();

        public int Compare(long x, long y)
        {
            if (x > y) return -1;
            if (x < y) return 1;
            return 0;
        }
    }

    public class ConsoleInput
    {
        private readonly char          _separator = ' ';
        private readonly TextReader    _stream;
        private readonly Queue<string> inputStream;

        public ConsoleInput(TextReader stream, char separator = ' ')
        {
            _separator  = separator;
            _stream     = stream;
            inputStream = new Queue<string>();
        }

        public string Read
        {
            get
            {
                if (inputStream.Count != 0)
                {
                    return inputStream.Dequeue();
                }

                var tmp = _stream.ReadLine().Split(_separator);
                for (var i = 0; i < tmp.Length; ++i)
                {
                    inputStream.Enqueue(tmp[i]);
                }

                return inputStream.Dequeue();
            }
        }

        public string ReadLine   => _stream.ReadLine();
        public int    ReadInt    => int.Parse(Read);
        public long   ReadLong   => long.Parse(Read);
        public double ReadDouble => double.Parse(Read);

        public string[] ReadStrArray(long N)
        {
            var ret = new string[N];
            for (long i = 0; i < N; ++i)
            {
                ret[i] = Read;
            }

            return ret;
        }

        public int[] ReadIntArray(long N)
        {
            var ret = new int[N];
            for (long i = 0; i < N; ++i)
            {
                ret[i] = ReadInt;
            }

            return ret;
        }

        public int[] ReadIntArrayMinus1(long N)
        {
            var ret = new int[N];
            for (long i = 0; i < N; ++i)
            {
                ret[i] = ReadInt - 1;
            }

            return ret;
        }

        public long[] ReadLongArray(long N)
        {
            var ret = new long[N];
            for (long i = 0; i < N; ++i)
            {
                ret[i] = ReadLong;
            }

            return ret;
        }
    }

    public interface IConsole
    {
        void Flush();
        void Write(object obj);
        void Write(string str);
        void WriteLine(object obj);
        void WriteLine(string str);
        void WriteLine();
    }

    public class MyConsole : IConsole
    {
        public MyConsole()
        {
            var sw = new StreamWriter(Console.OpenStandardOutput()) {AutoFlush = false};
            Console.SetOut(sw);
        }

        public void Flush()
        {
            Console.Out.Flush();
        }

        public void Write(object obj)
        {
            Write(obj.ToString());
        }

        public void Write(string str)
        {
            Console.Write(str);
        }

        public void WriteLine(object obj)
        {
            WriteLine(obj.ToString());
        }

        public void WriteLine(string str)
        {
            Console.WriteLine(str);
        }

        public void WriteLine()
        {
            Console.WriteLine();
        }
    }

#if UTAKA_LOCAL

    public class DebugConsole : IConsole
    {
        private readonly StringBuilder mSb;

        public DebugConsole()
        {
            mSb = new StringBuilder();
        }

        public void Flush()
        {
            // 何もしない
        }

        public void Write(object obj)
        {
            Write(obj.ToString());
        }

        public void Write(string str)
        {
            mSb.Append(str);
        }

        public void WriteLine(object obj)
        {
            WriteLine(obj.ToString());
        }

        public void WriteLine(string str)
        {
            mSb.AppendLine(str);
        }

        public void WriteLine()
        {
            mSb.AppendLine();
        }

        public string GetAllOutput()
        {
            return mSb.ToString();
        }
    }

#endif

#if UTAKA_LOCAL

    public class TestCaseCheckerForAtCoder
    {
        private string GetDirectoryPath()
        {
            var problemPart = string.IsNullOrEmpty(Program.ProblemName)
                ? ""
                : $"/{Program.ProblemName}";

            return
                $"{Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)}/AlgorithmPrac/{Program.SiteName}/{Program.ContestName}{problemPart}";
        }

        private string GetInputFilePath(int testCaseNumber)
        {
            return $"{GetDirectoryPath()}/sample-{testCaseNumber}.in";
        }

        private string GetOutputFilePath(int testCaseNumber)
        {
            return $"{GetDirectoryPath()}/sample-{testCaseNumber}.out";
        }

        public bool TestProblem(int testCaseNumber)
        {
            var inputFilePath  = GetInputFilePath(testCaseNumber);
            var outputFilePath = GetOutputFilePath(testCaseNumber);

            TextReader inputStream = new StreamReader(inputFilePath);
            var        cin         = new ConsoleInput(inputStream);

            var debugConsoleWriter = new DebugConsole();

            new Program(cin, debugConsoleWriter).Solve();

            var output = debugConsoleWriter.GetAllOutput();

            TextReader outputStream = new StreamReader(outputFilePath);
            var        outputAnswer = outputStream.ReadToEnd();

            Dbg.WriteLine(output);
            Dbg.WriteLine(outputAnswer);

            var isCorrect = output == outputAnswer;

            return isCorrect;
        }

        public void TestProblems(int targetTestCaseNumber = -1)
        {
            if (targetTestCaseNumber >= 0)
            {
                Console.WriteLine($"!!!!!!!!!!!! Check TestCase {targetTestCaseNumber} !!!!!!!!!!");
            }

            bool isSuccessAll = true;

            int testCaseNumber = 0;
            while (true)
            {
                testCaseNumber++;

                bool foundTargetTest = targetTestCaseNumber == testCaseNumber;

                if (targetTestCaseNumber >= 0 && !foundTargetTest)
                {
                    continue;
                }

                var inputFileName = GetInputFilePath(testCaseNumber);
                if (!File.Exists(inputFileName))
                {
                    break;
                }

                Console.WriteLine($"TestCase {testCaseNumber} =====================================================");

                var result = TestProblem(testCaseNumber);

                if (result)
                {
                    Console.WriteLine("Success");
                }
                else
                {
                    isSuccessAll = false;
                    Console.WriteLine("Failure *****");
                }

                if (foundTargetTest)
                {
                    break;
                }
            }

            if (isSuccessAll)
            {
                Console.WriteLine("!!!!!!!!! All Success !!!!!!!!!");
            }
        }
    }

#endif

    public static class Dbg
    {
        [Conditional("UTAKA_DEBUG")]
        public static void WriteLine(string str)
        {
            Console.WriteLine(str);
        }

        [Conditional("UTAKA_DEBUG")]
        public static void WriteLine()
        {
            Console.WriteLine();
        }

        [Conditional("UTAKA_DEBUG")]
        public static void Write(string str)
        {
            Console.Write(str);
        }
    }
}