AOJ本の読書メモ   AOJ    次のAOJの問題へ    前のAOJの問題へ

ALDS1_3_D: Areas on the Cross-Section Diagram


問題へのリンク


C#のソース

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

// Q010 水たまりの面積 https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_3_D&lang=jp
class Program
{
    static string InputPattern = "InputX";

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

        if (InputPattern == "Input1") {
            WillReturn.Add(@"\\//");
            //4
            //1 4
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add(@"\\///\_/\/\\\\/_/\\///__\\\_\\/_\/_/\");
            //35
            //5 4 2 1 19 9
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static void Main()
    {
        List<string> InputList = GetInputList();
        string InputStr = InputList[0].Replace('\\', '下');
        InputStr = InputStr.Replace('/', '上');

        var Stk = new Stack<int>();

        // 開始位置[水たまりの面積]なDict
        var WaterDict = new Dictionary<int, int>();

        for (int I = 0; I <= InputStr.Length - 1; I++) {
            if (InputStr[I] == '上' && Stk.Count > 0) {
                int PoppedInd = Stk.Pop();

                int CurrMenseki = 0;
                if (PoppedInd + 1 == I) { // 三角形の場合
                    CurrMenseki = 1;
                }
                else { // 台形の場合
                    int Jyoutei = I - PoppedInd + 1;
                    int Katei = Jyoutei - 2;
                    CurrMenseki = (Jyoutei + Katei) / 2;
                }

                // 水たまりの合併処理
                for (int J = PoppedInd + 1; J <= I - 1; J++) {
                    if (WaterDict.ContainsKey(J) == false) {
                        continue;
                    }
                    CurrMenseki += WaterDict[J];
                    WaterDict.Remove(J);
                }
                WaterDict[I] = CurrMenseki;
            }
            if (InputStr[I] == '下') {
                Stk.Push(I);
            }
        }
        Console.WriteLine(WaterDict.Sum(pX => pX.Value));

        int[] KeysArr = WaterDict.Keys.ToArray();
        Array.Sort(KeysArr);

        var WillOutList = new List<int>();
        WillOutList.Add(KeysArr.Length);
        for (int I = 0; I <= KeysArr.GetUpperBound(0); I++) {
            WillOutList.Add(WaterDict[KeysArr[I]]);
        }
        int[] WillOutArr = WillOutList.ToArray();
        Console.WriteLine(string.Join(" ", Array.ConvertAll(WillOutArr, pX => pX.ToString())));
    }
}


解説

Stackで水たまりの作成を管理しつつ、
水たまりのマージ処理も行ってます。