競技プログラミングの鉄則
次の問題へ
前の問題へ
B14 Another Subset Sum
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 30");
WillReturn.Add("5 1 18 7 2 9");
//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();
var OddList = new List<long>();
var EvenList = new List<long>();
for (int I = 0; I <= AArr.GetUpperBound(0); I++) {
if (I % 2 == 0) EvenList.Add(AArr[I]);
if (I % 2 == 1) OddList.Add(AArr[I]);
}
HashSet<long> SumSet1 = DeriveSumSet(EvenList);
HashSet<long> SumSet2 = DeriveSumSet(OddList);
if (SumSet1.Contains(K) || SumSet2.Contains(K)) {
Console.WriteLine("Yes");
return;
}
foreach (long EachVal in SumSet1) {
long NeedVal = K - EachVal;
if (SumSet2.Contains(NeedVal)) {
Console.WriteLine("Yes");
return;
}
}
Console.WriteLine("No");
}
// Listを引数として和のSetを返す
static HashSet<long> DeriveSumSet(List<long> pList)
{
var DPSet = new HashSet<long>();
DPSet.Add(0);
foreach (long EachVal in pList) {
foreach (long EachSum in DPSet.ToArray()) {
DPSet.Add(EachSum + EachVal);
}
}
return DPSet;
}
}
解説
半分全列挙で解いてます。