AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC374-C Separated Lunch
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 3 5 10 12");
//17
}
else if (InputPattern == "Input2") {
WillReturn.Add("2");
WillReturn.Add("1 1");
//1
}
else if (InputPattern == "Input3") {
WillReturn.Add("6");
WillReturn.Add("22 25 26 45 22 31");
//89
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
int K = int.Parse(InputList[0]);
long[] KArr = InputList[1].Split(' ').Select(pX => long.Parse(pX)).ToArray();
var BaseList = new List<long>();
BaseList.Add(0);
BaseList.Add(1);
var AnswerList = new List<long>();
foreach (long[] EachArr in RubyPatternClass<long>.RepeatedPermutation(BaseList, K)) {
long Sum0 = 0;
long Sum1 = 0;
for (int I = 0; I <= KArr.GetUpperBound(0); I++) {
if (EachArr[I] == 0) Sum0 += KArr[I];
if (EachArr[I] == 1) Sum1 += KArr[I];
}
AnswerList.Add(Math.Max(Sum0, Sum1));
}
Console.WriteLine(AnswerList.Min());
}
}
#region RubyPatternClass
// Rubyの場合の数
internal static class RubyPatternClass<Type>
{
// 重複順列を返す
private struct JyoutaiDef_RepeatedPermutation
{
internal List<int> SelectedIndList;
}
internal static IEnumerable<Type[]> RepeatedPermutation(IEnumerable<Type> pEnum, int pR)
{
if (pR == 0) yield break;
Type[] pArr = pEnum.ToArray();
var Stk = new Stack<JyoutaiDef_RepeatedPermutation>();
JyoutaiDef_RepeatedPermutation WillPush;
for (int I = pArr.GetUpperBound(0); 0 <= I; I--) {
WillPush.SelectedIndList = new List<int>() { I };
Stk.Push(WillPush);
}
while (Stk.Count > 0) {
JyoutaiDef_RepeatedPermutation Popped = Stk.Pop();
// クリア判定
if (Popped.SelectedIndList.Count == pR) {
var WillReturn = new List<Type>();
Popped.SelectedIndList.ForEach(X => WillReturn.Add(pArr[X]));
yield return WillReturn.ToArray();
continue;
}
for (int I = pArr.GetUpperBound(0); 0 <= I; I--) {
WillPush.SelectedIndList = new List<int>(Popped.SelectedIndList) { I };
Stk.Push(WillPush);
}
}
}
}
#endregion
解説
0と1からなる重複順列を求めて、解候補を列挙してます。