AOJ本の読書メモ
AOJ
次のAOJの問題へ
前のAOJの問題へ
AOJ 0507 Square
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("5");
WillReturn.Add("0");
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
static void Main()
{
List<string> InputList = GetInputList();
foreach (string EachStr in InputList) {
int CurrN = int.Parse(EachStr);
if (CurrN == 0) break;
Solve(CurrN);
}
}
struct JyoutaiDef
{
internal List<int> SelectedValList;
}
static void Solve(int pN)
{
var Stk = new Stack<JyoutaiDef>();
JyoutaiDef WillPush;
WillPush.SelectedValList = new List<int>();
Stk.Push(WillPush);
while (Stk.Count > 0) {
JyoutaiDef Popped = Stk.Pop();
// クリア判定
int SumVal = Popped.SelectedValList.Sum();
if (SumVal == pN) {
string[] StrArr =
Array.ConvertAll(Popped.SelectedValList.ToArray(), pX => pX.ToString());
Console.WriteLine(string.Join(" ", StrArr));
continue;
}
int MinVal = pN;
if (Popped.SelectedValList.Count > 0) {
MinVal = Popped.SelectedValList.Last();
}
int Rest = pN - SumVal;
for (int I = 1; I <= Math.Min(MinVal, Rest); I++) {
WillPush.SelectedValList = new List<int>(Popped.SelectedValList);
WillPush.SelectedValList.Add(I);
Stk.Push(WillPush);
}
}
}
}
解説
ナイーブにDFSしてます。