AtCoderのPAST
次のPASTの問題へ
前のPASTの問題へ
第19回PAST J 3人組
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("2");
WillReturn.Add("1 3 4 6 2 9");
//1
}
else if (InputPattern == "Input2") {
WillReturn.Add("2");
WillReturn.Add("0 0 0 0 0 100000000");
//100000000
}
else if (InputPattern == "Input3") {
WillReturn.Add("5");
WillReturn.Add("614 490 420 945 613 585 760 38 926 725 667 685 449 455 873");
//35
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static int[] mAArr;
static int UB;
static void Main()
{
List<string> InputList = GetInputList();
mAArr = InputList[1].Split(' ').Select(pX => int.Parse(pX)).ToArray();
UB = mAArr.GetUpperBound(0);
var Stk = new Stack<JyoutaiDef>();
JyoutaiDef WillPush;
WillPush.SelectedIndList = new List<int>();
Stk.Push(WillPush);
int Answer = int.MaxValue;
while (Stk.Count > 0) {
JyoutaiDef Popped = Stk.Pop();
if (Popped.SelectedIndList.Count == mAArr.Length) {
int CurrAnswer = DeriveAnswer(Popped.SelectedIndList);
Answer = Math.Min(Answer, CurrAnswer);
continue;
}
// 未使用番号の最小値を使う
int UseMin = 0;
for (int I = 0; I <= UB; I++) {
if (Popped.SelectedIndList.Contains(I)) {
UseMin++;
}
else {
break;
}
}
for (int I = UseMin + 1; I <= UB; I++) {
if (Popped.SelectedIndList.Contains(I)) continue;
for (int J = I + 1; J <= UB; J++) {
if (Popped.SelectedIndList.Contains(J)) continue;
WillPush.SelectedIndList = new List<int>(Popped.SelectedIndList);
WillPush.SelectedIndList.Add(UseMin);
WillPush.SelectedIndList.Add(I);
WillPush.SelectedIndList.Add(J);
Stk.Push(WillPush);
}
}
}
Console.WriteLine(Answer);
}
// 解候補を返す
static int DeriveAnswer(List<int> pIndList)
{
var SumList = new List<int>();
for (int I = 0; I <= UB; I += 3) {
int CurrSum = 0;
CurrSum += mAArr[pIndList[I + 0]];
CurrSum += mAArr[pIndList[I + 1]];
CurrSum += mAArr[pIndList[I + 2]];
SumList.Add(CurrSum);
}
return SumList.Max() - SumList.Min();
}
struct JyoutaiDef
{
internal List<int> SelectedIndList;
}
}
解説
15C3 = 455
12C3 = 220
9C3 = 84
6C3 = 20
で455*220*84*20 = 168168000
なので組み合わせをDFSで列挙してます。
計算量削減で、未使用番号の最小値を必ず使うようにしてます。