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

A14 Four Boxes


問題へのリンク


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("3 50");
            WillReturn.Add("3 9 17");
            WillReturn.Add("4 7 9");
            WillReturn.Add("10 20 30");
            WillReturn.Add("1 2 3");
            //Yes
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

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

        long[] AArr = InputList[1].Split(' ').Select(pX => long.Parse(pX)).ToArray();
        long[] BArr = InputList[2].Split(' ').Select(pX => long.Parse(pX)).ToArray();
        long[] CArr = InputList[3].Split(' ').Select(pX => long.Parse(pX)).ToArray();
        long[] DArr = InputList[4].Split(' ').Select(pX => long.Parse(pX)).ToArray();

        HashSet<long> SumSet1 = DeriveSumSet(AArr, BArr);
        HashSet<long> SumSet2 = DeriveSumSet(CArr, DArr);

        foreach (long EachSum in SumSet1) {
            long Rest = K - EachSum;
            if (SumSet2.Contains(Rest)) {
                Console.WriteLine("Yes");
                return;
            }
        }
        Console.WriteLine("No");
    }

    // 配列2つを引数として和のSetを返す
    static HashSet<long> DeriveSumSet(long[] pArr1, long[] pArr2)
    {
        var WillReturn = new HashSet<long>();
        foreach (long EachVal1 in pArr1) {
            foreach (long EachVal2 in pArr2) {
                WillReturn.Add(EachVal1 + EachVal2);
            }

        }
        return WillReturn;
    }
}


解説

半分全列挙で解いてます。