yukicoder    次のyukicoderの問題へ    前のyukicoderの問題へ

yukicoder 2924 Super Spaceship String


問題へのリンク


C#のソース

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("<=<<==>=><>");
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add(">=<=<>=>=<");
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static void Main()
    {
        List<string> InputList = GetInputList();
        string S = InputList[0];

        var InsLinkedList = new LinkedList<RunLenInfo>();
        foreach (char EachChar in S) {

            var WillAdd = new RunLenInfo();
            WillAdd.AppearChar = EachChar;
            WillAdd.RunLen = 1;
            InsLinkedList.AddLast(WillAdd);

            while (true) {
                if (ExecConcat(InsLinkedList)) continue;
                if (ExecRemove(InsLinkedList)) continue;
                break;
            }
        }
        long Answer = InsLinkedList.Sum(pX => pX.RunLen);
        Console.WriteLine(Answer);
    }

    // =同士の接続処理を行い、変更有無を返す
    static bool ExecConcat(LinkedList<RunLenInfo> pLinkedList)
    {
        bool Changed = false;
        while (true) {
            if (pLinkedList.Count >= 2) {
                char Last2 = pLinkedList.Last.Value.AppearChar;
                char Last1 = pLinkedList.Last.Previous.Value.AppearChar;

                if (Last1 == '=' && Last2 == '=') {
                    pLinkedList.Last.Previous.Value.RunLen += pLinkedList.Last.Value.RunLen;
                    pLinkedList.RemoveLast();
                    Changed = true;
                    continue;
                }
            }
            return Changed;
        }
    }

    // 宇宙船の削除処理を行い、変更有無を返す
    static bool ExecRemove(LinkedList<RunLenInfo> pLinkedList)
    {
        bool Changed = false;
        while (true) {
            if (pLinkedList.Count >= 3) {
                char Last3 = pLinkedList.Last.Value.AppearChar;
                char Last2 = pLinkedList.Last.Previous.Value.AppearChar;
                char Last1 = pLinkedList.Last.Previous.Previous.Value.AppearChar;

                if (Last1 == '<' && Last2 == '=' && Last3 == '>') {
                    pLinkedList.RemoveLast();
                    pLinkedList.RemoveLast();
                    pLinkedList.RemoveLast();
                    Changed = true;
                    continue;
                }
            }
            return Changed;
        }
    }

    // ランレングス圧縮情報
    internal class RunLenInfo
    {
        internal char AppearChar;
        internal int RunLen;
    }
}


解説

ランレングス結果をLinkedListで管理してます。