AtCoderのABC    次のABCの問題へ    前のABCの問題へ

ABC181-D Hachi


問題へのリンク


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

    struct JyoutaiDef
    {
        internal HashSet<int> SelectedIndSet;
        internal string CurrStr;
    }

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

        var Stk = new Stack<JyoutaiDef>();
        JyoutaiDef WillPush;
        WillPush.SelectedIndSet = new HashSet<int>();
        WillPush.CurrStr = "";
        Stk.Push(WillPush);

        var VisitedSet = new HashSet<string>();
        while (Stk.Count > 0) {
            JyoutaiDef Popped = Stk.Pop();

            if (Popped.CurrStr.Length == S.Length || Popped.CurrStr.Length == 3) {
                if (long.Parse(Popped.CurrStr) % 8 == 0) {
                    Console.WriteLine("Yes");
                    return;
                }
                continue;
            }

            for (int I = 0; I <= S.Length - 1; I++) {
                if (Popped.SelectedIndSet.Contains(I)) continue;
                WillPush.CurrStr = Popped.CurrStr + S[I];

                if (VisitedSet.Add(WillPush.CurrStr)) {
                    WillPush.SelectedIndSet = new HashSet<int>(Popped.SelectedIndSet);
                    WillPush.SelectedIndSet.Add(I);
                    Stk.Push(WillPush);
                }
            }
        }
        Console.WriteLine("No");
    }
}


解説

1000は125*8なので、
数値が8の倍数かを判定するには、
下3桁が8の倍数かを判定すればいいです。

なので、深さ優先探索で、下3桁の数値を列挙してます。