AtCoderのABC    次のABCの問題へ    前のABCの問題へ

ABC241-F Skate


問題へのリンク


C#のソース(Listクラスを使う方法)

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static string InputPattern = "InputX";

    static List<string> GetInputList()
    {
        var WillReturn = new List<string>();

        if (InputPattern == "Input1") {
            WillReturn.Add("7 8 7");
            WillReturn.Add("3 4");
            WillReturn.Add("5 6");
            WillReturn.Add("1 4");
            WillReturn.Add("2 1");
            WillReturn.Add("2 8");
            WillReturn.Add("4 5");
            WillReturn.Add("5 7");
            WillReturn.Add("6 2");
            WillReturn.Add("6 6");
            //4
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("4 6 2");
            WillReturn.Add("3 2");
            WillReturn.Add("3 5");
            WillReturn.Add("4 5");
            WillReturn.Add("2 5");
            //-1
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("1 10 1");
            WillReturn.Add("1 5");
            WillReturn.Add("1 1");
            WillReturn.Add("1 7");
            //-1
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static int mStaX;
    static int mStaY;
    static int mEndX;
    static int mEndY;

    struct XYInfoDef
    {
        internal int X;
        internal int Y;
    }
    static List<XYInfoDef> mXYInfoList = new List<XYInfoDef>();

    // X座標ごとのY座標のList
    static Dictionary<int, List<int>> mYListDict = new Dictionary<int, List<int>>();

    // Y座標ごとのX座標のList
    static Dictionary<int, List<int>> mXListDict = new Dictionary<int, List<int>>();

    static void Main()
    {
        List<string> InputList = GetInputList();

        int[] wkArr = { };
        Action<string> SplitAct = pStr =>
            wkArr = pStr.Split(' ').Select(pX => int.Parse(pX)).ToArray();

        SplitAct(InputList[1]);
        mStaX = wkArr[1];
        mStaY = wkArr[0];

        SplitAct(InputList[2]);
        mEndX = wkArr[1];
        mEndY = wkArr[0];

        foreach (string EachStr in InputList.Skip(3)) {
            SplitAct(EachStr);
            XYInfoDef WillAdd;
            WillAdd.X = wkArr[1];
            WillAdd.Y = wkArr[0];
            mXYInfoList.Add(WillAdd);
        }

        foreach (XYInfoDef EachXYInfo in mXYInfoList) {
            int CurrX = EachXYInfo.X;
            int CurrY = EachXYInfo.Y;

            if (mYListDict.ContainsKey(CurrX) == false) {
                mYListDict[CurrX] = new List<int>();
            }
            mYListDict[CurrX].Add(CurrY);

            if (mXListDict.ContainsKey(CurrY) == false) {
                mXListDict[CurrY] = new List<int>();
            }
            mXListDict[CurrY].Add(CurrX);
        }

        foreach (var EachPair in mYListDict) {
            EachPair.Value.Sort();
        }
        foreach (var EachPair in mXListDict) {
            EachPair.Value.Sort();
        }

        ExecBFS();
    }

    struct JyoutaiDef
    {
        internal int CurrX;
        internal int CurrY;
        internal int Level;
    }

    static void ExecBFS()
    {
        var Que = new Queue<JyoutaiDef>();
        JyoutaiDef WillEnqueue;
        WillEnqueue.CurrX = mStaX;
        WillEnqueue.CurrY = mStaY;
        WillEnqueue.Level = 0;
        Que.Enqueue(WillEnqueue);

        var VisitedSet = new HashSet<long>();

        while (Que.Count > 0) {
            JyoutaiDef Dequeued = Que.Dequeue();

            // クリア判定
            if (Dequeued.CurrX == mEndX && Dequeued.CurrY == mEndY) {
                Console.WriteLine(Dequeued.Level);
                return;
            }

            Action<int, int> EnqueueAct = (pNewX, pNewY) =>
            {
                long Hash = (long)pNewX * 1000000000 + pNewY;
                if (VisitedSet.Add(Hash)) {
                    WillEnqueue.CurrX = pNewX;
                    WillEnqueue.CurrY = pNewY;
                    WillEnqueue.Level = Dequeued.Level + 1;
                    Que.Enqueue(WillEnqueue);
                }
            };

            if (mYListDict.ContainsKey(Dequeued.CurrX)) {
                int UpperB = ExecNibunhou_UpperBound(Dequeued.CurrY, mYListDict[Dequeued.CurrX]);
                if (UpperB > -1) {
                    // 下に移動
                    EnqueueAct(Dequeued.CurrX, mYListDict[Dequeued.CurrX][UpperB] - 1);
                }
                int Lower_Max = ExecNibunhou_LowerMax(Dequeued.CurrY, mYListDict[Dequeued.CurrX]);
                if (Lower_Max > -1) {
                    // 上に移動
                    EnqueueAct(Dequeued.CurrX, mYListDict[Dequeued.CurrX][Lower_Max] + 1);
                }
            }

            if (mXListDict.ContainsKey(Dequeued.CurrY)) {
                int UpperB = ExecNibunhou_UpperBound(Dequeued.CurrX, mXListDict[Dequeued.CurrY]);
                if (UpperB > -1) {
                    // 右に移動
                    EnqueueAct(mXListDict[Dequeued.CurrY][UpperB] - 1, Dequeued.CurrY);
                }
                int Lower_Max = ExecNibunhou_LowerMax(Dequeued.CurrX, mXListDict[Dequeued.CurrY]);
                if (Lower_Max > -1) {
                    // 左に移動
                    EnqueueAct(mXListDict[Dequeued.CurrY][Lower_Max] + 1, Dequeued.CurrY);
                }
            }
        }
        Console.WriteLine(-1);
    }

    // 二分法で、Val超えで最小の値を持つ、添字を返す (List版)
    static int ExecNibunhou_UpperBound(int pVal, List<int> pList)
    {
        // 最後の要素がVal以下の特殊ケース
        if (pVal >= pList.Last()) {
            return -1;
        }
        // 最初の要素がVal超えの特殊ケース
        if (pVal < pList[0]) {
            return 0;
        }

        int L = 0;
        int R = pList.Count - 1;

        while (L + 1 < R) {
            int Mid = (L + R) / 2;

            if (pList[Mid] > pVal) {
                R = Mid;
            }
            else {
                L = Mid;
            }
        }
        return R;
    }

    // 二分法で、Val未満で最大の値を持つ、添字を返す (List版)
    static int ExecNibunhou_LowerMax(int pVal, List<int> pList)
    {
        // 最後の要素がVal未満の特殊ケース
        if (pVal > pList.Last()) {
            return pList.Count - 1;
        }
        // 最初の要素がVal以上の特殊ケース
        if (pVal <= pList[0]) {
            return -1;
        }

        int L = 0;
        int R = pList.Count - 1;

        while (L + 1 < R) {
            int Mid = (L + R) / 2;

            if (pList[Mid] < pVal) {
                L = Mid;
            }
            else {
                R = Mid;
            }
        }
        return L;
    }
}


C#のソース(AVL木でC++のsetを模倣する方法)

using System;
using System.Collections.Generic;
using System.Linq;

class Program
{
    static string InputPattern = "InputX";

    static List<string> GetInputList()
    {
        var WillReturn = new List<string>();

        if (InputPattern == "Input1") {
            WillReturn.Add("7 8 7");
            WillReturn.Add("3 4");
            WillReturn.Add("5 6");
            WillReturn.Add("1 4");
            WillReturn.Add("2 1");
            WillReturn.Add("2 8");
            WillReturn.Add("4 5");
            WillReturn.Add("5 7");
            WillReturn.Add("6 2");
            WillReturn.Add("6 6");
            //4
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("4 6 2");
            WillReturn.Add("3 2");
            WillReturn.Add("3 5");
            WillReturn.Add("4 5");
            WillReturn.Add("2 5");
            //-1
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("1 10 1");
            WillReturn.Add("1 5");
            WillReturn.Add("1 1");
            WillReturn.Add("1 7");
            //-1
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static int mStaX;
    static int mStaY;
    static int mEndX;
    static int mEndY;

    struct XYInfoDef
    {
        internal int X;
        internal int Y;
    }
    static List<XYInfoDef> mXYInfoList = new List<XYInfoDef>();

    // X座標ごとのY座標のset
    static Dictionary<int, AVL_Set_MultiSet<int>> mYSetDict = new Dictionary<int, AVL_Set_MultiSet<int>>();

    // Y座標ごとのX座標のset
    static Dictionary<int, AVL_Set_MultiSet<int>> mXSetDict = new Dictionary<int, AVL_Set_MultiSet<int>>();

    static void Main()
    {
        List<string> InputList = GetInputList();

        int[] wkArr = { };
        Action<string> SplitAct = pStr =>
            wkArr = pStr.Split(' ').Select(pX => int.Parse(pX)).ToArray();

        SplitAct(InputList[1]);
        mStaX = wkArr[1];
        mStaY = wkArr[0];

        SplitAct(InputList[2]);
        mEndX = wkArr[1];
        mEndY = wkArr[0];

        foreach (string EachStr in InputList.Skip(3)) {
            SplitAct(EachStr);
            XYInfoDef WillAdd;
            WillAdd.X = wkArr[1];
            WillAdd.Y = wkArr[0];
            mXYInfoList.Add(WillAdd);
        }

        foreach (XYInfoDef EachXYInfo in mXYInfoList) {
            int CurrX = EachXYInfo.X;
            int CurrY = EachXYInfo.Y;

            if (mYSetDict.ContainsKey(CurrX) == false) {
                mYSetDict[CurrX] = new AVL_Set_MultiSet<int>();
            }
            mYSetDict[CurrX].Add(CurrY);

            if (mXSetDict.ContainsKey(CurrY) == false) {
                mXSetDict[CurrY] = new AVL_Set_MultiSet<int>();
            }
            mXSetDict[CurrY].Add(CurrX);
        }
        ExecBFS();
    }

    struct JyoutaiDef
    {
        internal int CurrX;
        internal int CurrY;
        internal int Level;
    }

    static void ExecBFS()
    {
        var Que = new Queue<JyoutaiDef>();
        JyoutaiDef WillEnqueue;
        WillEnqueue.CurrX = mStaX;
        WillEnqueue.CurrY = mStaY;
        WillEnqueue.Level = 0;
        Que.Enqueue(WillEnqueue);

        var VisitedSet = new HashSet<long>();

        while (Que.Count > 0) {
            JyoutaiDef Dequeued = Que.Dequeue();

            // クリア判定
            if (Dequeued.CurrX == mEndX && Dequeued.CurrY == mEndY) {
                Console.WriteLine(Dequeued.Level);
                return;
            }

            Action<int, int> EnqueueAct = (pNewX, pNewY) =>
            {
                long Hash = (long)pNewX * 1000000000 + pNewY;
                if (VisitedSet.Add(Hash)) {
                    WillEnqueue.CurrX = pNewX;
                    WillEnqueue.CurrY = pNewY;
                    WillEnqueue.Level = Dequeued.Level + 1;
                    Que.Enqueue(WillEnqueue);
                }
            };

            if (mYSetDict.ContainsKey(Dequeued.CurrX)) {
                int UpperB = mYSetDict[Dequeued.CurrX].UpperBound(Dequeued.CurrY);
                if (mYSetDict[Dequeued.CurrX].IsValidInd(UpperB)) {
                    // 下に移動
                    EnqueueAct(Dequeued.CurrX, mYSetDict[Dequeued.CurrX][UpperB] - 1);
                }
                int Lower_Max = mYSetDict[Dequeued.CurrX].Lower_Max(Dequeued.CurrY);
                if (mYSetDict[Dequeued.CurrX].IsValidInd(Lower_Max)) {
                    // 上に移動
                    EnqueueAct(Dequeued.CurrX, mYSetDict[Dequeued.CurrX][Lower_Max] + 1);
                }
            }

            if (mXSetDict.ContainsKey(Dequeued.CurrY)) {
                int UpperB = mXSetDict[Dequeued.CurrY].UpperBound(Dequeued.CurrX);
                if (mXSetDict[Dequeued.CurrY].IsValidInd(UpperB)) {
                    // 右に移動
                    EnqueueAct(mXSetDict[Dequeued.CurrY][UpperB] - 1, Dequeued.CurrY);
                }
                int Lower_Max = mXSetDict[Dequeued.CurrY].Lower_Max(Dequeued.CurrX);
                if (mXSetDict[Dequeued.CurrY].IsValidInd(Lower_Max)) {
                    // 左に移動
                    EnqueueAct(mXSetDict[Dequeued.CurrY][Lower_Max] + 1, Dequeued.CurrY);
                }
            }

        }
        Console.WriteLine(-1);
    }
}

#region AVL_Set_MultiSet
/// <summary>
/// 要素の追加、削除、検索、取得が可能な集合を表します.
/// </summary>
/// <typeparam name="T">優先度付きキュー内の要素の型を指定します.</typeparam>
/// <remarks>内部的にはAVL木によって実装されています.</remarks>
internal class AVL_Set_MultiSet<T>
{
    Node root;
    readonly IComparer<T> comparer;
    readonly Node nil;

    /// <summary>
    /// 多重集合かどうかを表します.
    /// </summary>
    internal bool IsMultiSet { get; set; }
    internal AVL_Set_MultiSet(IComparer<T> comparer)
    {
        nil = new Node(default(T));
        root = nil;
        this.comparer = comparer;
    }

    internal AVL_Set_MultiSet() : this(Comparer<T>.Default) { }

    /// <summary>
    /// 要素をコレクションに追加します.
    /// </summary>
    /// <remarks>この操作は計算量 O(log N) で実行されます.</remarks>
    internal bool Add(T v)
    {
        return insert(ref root, v);
    }

    /// <summary>
    /// v が存在するならコレクションから削除します.
    /// </summary>
    /// <remarks>この操作は計算量 O(log N) で実行されます.</remarks>
    internal bool Remove(T v)
    {
        return remove(ref root, v);
    }

    /// <summary>
    /// 0-indexed で index 番目の要素をコレクションから取得します.
    /// </summary>
    /// <remarks>この操作は計算量 O(log N) で実行されます.</remarks>
    internal T this[int index] { get { return find(root, index); } }
    internal int Count { get { return root.Count; } }

    internal void RemoveAt(int k)
    {
        if (k < 0 || k >= root.Count) throw new ArgumentOutOfRangeException();
        removeAt(ref root, k);
    }

    /// <summary>
    /// このコレクションに含まれる要素を昇順に並べて返します.
    /// </summary>
    /// <remarks>この操作は計算量 O(N) で実行されます.</remarks>
    internal T[] Items
    {
        get
        {
            T[] ret = new T[root.Count];
            int k = 0;
            walk(root, ret, ref k);
            return ret;
        }
    }

    private void walk(Node t, T[] a, ref int k)
    {
        if (t.Count == 0) return;
        walk(t.lst, a, ref k);
        a[k++] = t.Key;
        walk(t.rst, a, ref k);
    }

    private bool insert(ref Node t, T key)
    {
        if (t.Count == 0) { t = new Node(key); t.lst = t.rst = nil; t.Update(); return true; }
        int cmp = comparer.Compare(t.Key, key);
        bool res;
        if (cmp > 0)
            res = insert(ref t.lst, key);
        else if (cmp == 0) {
            if (IsMultiSet) res = insert(ref t.lst, key);
            else return false;
        }
        else res = insert(ref t.rst, key);
        balance(ref t);
        return res;
    }

    private bool remove(ref Node t, T key)
    {
        if (t.Count == 0) return false;
        int cmp = comparer.Compare(key, t.Key);
        bool ret;
        if (cmp < 0) ret = remove(ref t.lst, key);
        else if (cmp > 0) ret = remove(ref t.rst, key);
        else {
            ret = true;
            var k = t.lst.Count;
            if (k == 0) { t = t.rst; return true; }
            if (t.rst.Count == 0) { t = t.lst; return true; }

            t.Key = find(t.lst, k - 1);
            removeAt(ref t.lst, k - 1);
        }
        balance(ref t);
        return ret;
    }

    private void removeAt(ref Node t, int k)
    {
        int cnt = t.lst.Count;
        if (cnt < k) removeAt(ref t.rst, k - cnt - 1);
        else if (cnt > k) removeAt(ref t.lst, k);
        else {
            if (cnt == 0) { t = t.rst; return; }
            if (t.rst.Count == 0) { t = t.lst; return; }

            t.Key = find(t.lst, k - 1);
            removeAt(ref t.lst, k - 1);
        }
        balance(ref t);
    }

    private void balance(ref Node t)
    {
        int balance = t.lst.Height - t.rst.Height;
        if (balance == -2) {
            if (t.rst.lst.Height - t.rst.rst.Height > 0) { rotR(ref t.rst); }
            rotL(ref t);
        }
        else if (balance == 2) {
            if (t.lst.lst.Height - t.lst.rst.Height < 0) rotL(ref t.lst);
            rotR(ref t);
        }
        else t.Update();
    }

    private T find(Node t, int k)
    {
        if (k < 0 || k > root.Count) throw new ArgumentOutOfRangeException();
        while (true) {
            if (k == t.lst.Count) return t.Key;
            else if (k < t.lst.Count) t = t.lst;
            else { k -= t.lst.Count + 1; t = t.rst; }
        }
    }
    /// <summary>
    /// コレクションに含まれる要素であって、 v 以上の最小の要素の番号を返します。
    /// </summary>
    /// <remarks>この操作は計算量 O(log N) で実行されます.</remarks>
    internal int LowerBound(T v)
    {
        // 追加機能 件数が0なら-1を返す
        if (this.Count == 0) {
            return -1;
        }

        // 追加機能 v 以上な要素が無い場合は-1を返す
        T MaxVal = this[this.Count - 1];
        int cmp = comparer.Compare(MaxVal, v);
        if (cmp == -1) return -1;

        int k = 0;
        Node t = root;
        while (true) {
            if (t.Count == 0) return k;
            if (comparer.Compare(v, t.Key) <= 0) t = t.lst;
            else { k += t.lst.Count + 1; t = t.rst; }
        }
    }
    /// <summary>
    /// コレクションに含まれる要素であって、 v より真に大きい、最小の要素の番号を返します。
    /// </summary>
    /// <remarks>この操作は計算量 O(log N) で実行されます.</remarks>
    internal int UpperBound(T v)
    {
        // 追加機能 件数が0なら-1を返す
        if (this.Count == 0) {
            return -1;
        }

        // 追加機能 v 超えな要素が無い場合は-1を返す
        T MaxVal = this[this.Count - 1];
        int cmp = comparer.Compare(MaxVal, v);
        if (cmp <= 0) return -1;

        int k = 0;
        Node t = root;
        while (true) {
            if (t.Count == 0) return k;
            if (comparer.Compare(t.Key, v) <= 0) { k += t.lst.Count + 1; t = t.rst; }
            else t = t.lst;
        }
    }

    // 追加機能 V未満で最大の要素の番号を返す
    internal int Lower_Max(T v)
    {
        // 件数が0なら-1を返す
        if (this.Count == 0) {
            return -1;
        }

        // v 未満な要素が無い場合は-1を返す
        T MinVal = this[0];
        int cmp = comparer.Compare(MinVal, v);
        if (cmp >= 0) return -1;

        // v 以上の件数を調べる
        int More_Or_Equal_cnt = this.Count;
        int UB = this.Count - 1;
        int LowerB = LowerBound(v);
        if (IsValidInd(LowerB)) {
            More_Or_Equal_cnt -= (UB - LowerB + 1);
        }
        return More_Or_Equal_cnt - 1;
    }

    // 追加機能 V以下で最大の要素の番号を返す
    internal int LowerOrEqual_Max(T v)
    {
        // 件数が0なら-1を返す
        if (this.Count == 0) {
            return -1;
        }

        // v 以下な要素が無い場合は-1を返す
        T MinVal = this[0];
        int cmp = comparer.Compare(MinVal, v);
        if (cmp > 0) return -1;

        // v 超えの件数を調べる
        int More_cnt = this.Count;
        int UB = this.Count - 1;
        int UpperB = UpperBound(v);
        if (IsValidInd(UpperB)) {
            More_cnt -= (UB - UpperB + 1);
        }
        return More_cnt - 1;
    }

    // 追加機能 LowerBoundなどで返したIndが、有効範囲かを判定
    internal bool IsValidInd(int pInd)
    {
        if (pInd < 0) return false;
        if (this.Count <= pInd) return false;
        return true;
    }

    // 追加機能 Vを含むかを返す
    internal bool Contains(T v)
    {
        int LowerB = LowerBound(v);
        if (IsValidInd(LowerB) == false) {
            return false;
        }
        int cmp = comparer.Compare(this[LowerB], v);
        return cmp == 0;
    }

    private void rotR(ref Node t)
    {
        Node l = t.lst;
        t.lst = l.rst;
        l.rst = t;
        t.Update();
        l.Update();
        t = l;
    }

    private void rotL(ref Node t)
    {
        Node r = t.rst;
        t.rst = r.lst;
        r.lst = t;
        t.Update();
        r.Update();
        t = r;
    }

    class Node
    {
        internal Node(T key)
        {
            Key = key;
        }
        internal int Count { get; private set; }
        internal int Height { get; private set; }
        internal T Key { get; set; }
        internal Node lst, rst;
        internal void Update()
        {
            Count = 1 + lst.Count + rst.Count;
            Height = 1 + Math.Max(lst.Height, rst.Height);
        }
        public override string ToString()
        {
            return string.Format("Count = {0}, Key = {1}", Count, Key);
        }
    }
}
#endregion


解説

BFSで解いてます。