AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC183-C Travel
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("4 330");
WillReturn.Add("0 1 10 100");
WillReturn.Add("1 0 20 200");
WillReturn.Add("10 20 0 300");
WillReturn.Add("100 200 300 0");
//2
}
else if (InputPattern == "Input2") {
WillReturn.Add("5 5");
WillReturn.Add("0 1 1 1 1");
WillReturn.Add("1 0 1 1 1");
WillReturn.Add("1 1 0 1 1");
WillReturn.Add("1 1 1 0 1");
WillReturn.Add("1 1 1 1 0");
//24
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
struct JyoutaiDef
{
internal int CurrPos;
internal HashSet<int> VisitedSet;
internal int CostSum;
}
static void Main()
{
List<string> InputList = GetInputList();
int[] wkArr = { };
Action<string> SplitAct = pStr =>
wkArr = pStr.Split(' ').Select(pX => int.Parse(pX)).ToArray();
SplitAct(InputList[0]);
int N = wkArr[0];
int K = wkArr[1];
int UB = N - 1;
int[,] MatrixArr = new int[UB + 1, UB + 1];
for (int I = 0; I <= UB; I++) {
SplitAct(InputList[1 + I]);
for (int J = 0; J <= UB; J++) {
MatrixArr[J, I] = wkArr[J];
}
}
var Stk = new Stack<JyoutaiDef>();
JyoutaiDef WillPush;
WillPush.CurrPos = 0;
WillPush.VisitedSet = new HashSet<int>();
WillPush.CostSum = 0;
Stk.Push(WillPush);
int Answer = 0;
while (Stk.Count > 0) {
JyoutaiDef Popped = Stk.Pop();
if (Popped.VisitedSet.Count == N) {
if (Popped.CurrPos == 0 && Popped.CostSum == K) {
Answer++;
}
continue;
}
for (int I = 0; I <= UB; I++) {
if (Popped.VisitedSet.Contains(I)) continue;
WillPush.CurrPos = I;
WillPush.CostSum = Popped.CostSum + MatrixArr[Popped.CurrPos, I];
WillPush.VisitedSet = new HashSet<int>(Popped.VisitedSet);
WillPush.VisitedSet.Add(I);
Stk.Push(WillPush);
}
}
Console.WriteLine(Answer);
}
}
解説
深さ優先探索してます。