競技プログラミングの鉄則    次の問題へ    前の問題へ

B42 Two Faced Cards


問題へのリンク


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("5");
            WillReturn.Add("2 8");
            WillReturn.Add("4 -5");
            WillReturn.Add("5 -3");
            WillReturn.Add("-4 1");
            WillReturn.Add("-2 -3");
            //18
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    struct ABInfoDef
    {
        internal long A;
        internal long B;
    }
    static List<ABInfoDef> mABInfoList = new List<ABInfoDef>();

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

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

        foreach (string EachStr in InputList.Skip(1)) {
            SplitAct(EachStr);
            ABInfoDef WillAdd;
            WillAdd.A = wkArr[0];
            WillAdd.B = wkArr[1];
            mABInfoList.Add(WillAdd);
        }

        long Answer = long.MinValue;
        Answer = Math.Max(Answer, DervieAnswer(-1, -1));
        Answer = Math.Max(Answer, DervieAnswer(-1, +1));
        Answer = Math.Max(Answer, DervieAnswer(+1, -1));
        Answer = Math.Max(Answer, DervieAnswer(+1, +1));
        Console.WriteLine(Answer);
    }

    static long DervieAnswer(long pSignA, long pSignB)
    {
        long CurrAnswer = 0;
        foreach (ABInfoDef EachABInfo in mABInfoList) {
            long CurrA = EachABInfo.A;
            long CurrB = EachABInfo.B;

            long CurrVal = CurrA * pSignA + CurrB * pSignB;
            if (CurrVal > 0) {
                CurrAnswer += CurrVal;
            }
        }
        return CurrAnswer;
    }
}


解説

最適解の、
表の合計の符号と
裏の合計の符号をして考えられるのは、
2*2で4通りです。

なので、この4通りを全て試してます。