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

B32 Game 5


問題へのリンク


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("8 2");
            WillReturn.Add("2 3");
            //First
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("6 2");
            WillReturn.Add("2 3");
            //Second
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("20 3");
            WillReturn.Add("6 1 3");
            //Second
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static long mN;
    static long[] mAArr;

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

        mAArr = InputList[1].Split(' ').Select(pX => long.Parse(pX)).ToArray();

        if (IsWin(mN)) {
            Console.WriteLine("First");
        }
        else {
            Console.WriteLine("Second");
        }
    }

    // 石の数を引数として、手番を持った方が勝ちかを返す
    static Dictionary<long, bool> mMemo = new Dictionary<long, bool>();
    static bool IsWin(long pStoneCnt)
    {
        if (mMemo.ContainsKey(pStoneCnt)) {
            return mMemo[pStoneCnt];
        }
        var SeniList = new List<long>();

        foreach (long EachA in mAArr) {
            if (pStoneCnt >= EachA) {
                SeniList.Add(pStoneCnt - EachA);
            }
        }

        if (SeniList.Count == 0) {
            return mMemo[pStoneCnt] = false;
        }

        // 相手を負けにできる手が、少なくとも1つあれば手番を持ったほうの勝ち
        if (SeniList.Exists(pX => IsWin(pX) == false)) {
            return mMemo[pStoneCnt] = true;
        }
        return mMemo[pStoneCnt] = false;
    }
}


解説

メモ化再帰で解いてます。