AtCoderのARC    次のARCの問題へ    前のARCの問題へ

ARC194-A Operations on a Stack


問題へのリンク


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("6");
            WillReturn.Add("3 -1 -4 5 -9 2");
            //8
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("1");
            WillReturn.Add("-1");
            //-1
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("20");
            WillReturn.Add("-14 74 -48 38 -51 43 5 37 -39 -29 80 -44 -55 59 17 89 -37 -68 38 -16");
            //369
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static void Main()
    {
        List<string> InputList = GetInputList();
        long[] AArr = InputList[1].Split(' ').Select(pX => long.Parse(pX)).ToArray();

        // 最大スコア[次に消すことが可能?]なDP表
        long?[] PrevDP = new long?[2];

        PrevDP[1] = AArr[0];

        long UB = AArr.GetUpperBound(0);
        for (long I = 1; I <= UB; I++) {
            long PrevVal = AArr[I - 1];
            long CurrVal = AArr[I];
            long?[] CurrDP = new long?[2];
            for (long J = 0; J <= 1; J++) {
                if (PrevDP[J].HasValue == false) continue;

                Action<long, long> UpsertAct = (pNewInd, pNewVal) =>
                {
                    if (CurrDP[pNewInd].HasValue) {
                        if (CurrDP[pNewInd].Value >= pNewVal) {
                            return;
                        }
                    }
                    CurrDP[pNewInd] = pNewVal;
                };

                if (J == 0) {
                    UpsertAct(1, PrevDP[J].Value + CurrVal);
                }
                if (J == 1) {
                    UpsertAct(0, PrevDP[J].Value - PrevVal);
                    UpsertAct(1, PrevDP[J].Value + CurrVal);
                }
            }
            PrevDP = CurrDP;
        }

        var AnswerList = new List<long>();
        if (PrevDP[0].HasValue) {
            AnswerList.Add(PrevDP[0].Value);
        }
        if (PrevDP[1].HasValue) {
            AnswerList.Add(PrevDP[1].Value);
        }
        Console.WriteLine(AnswerList.Max());
    }
}


解説

○○○○○○○○○○
といった図で考えると
偶数長の長さに限って除外できるので

任意の位置から、2つペアで取る取らないを繰り返すと考えることができます。

なので、最大スコア[次に消すことが可能?]を更新するDPで解けます。