AOJ本の読書メモ
AOJ
次のAOJの問題へ
前のAOJの問題へ
ALDS1_11_D: Connected Components
C#のソース
using System;
using System.Collections.Generic;
using System.Linq;
// Q039 連結成分 https://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=ALDS1_11_D&lang=jp
class Program
{
static string InputPattern = "InputX";
static List<string> GetInputList()
{
var WillReturn = new List<string>();
if (InputPattern == "Input1") {
WillReturn.Add("10 9");
WillReturn.Add("0 1");
WillReturn.Add("0 2");
WillReturn.Add("3 4");
WillReturn.Add("5 7");
WillReturn.Add("5 6");
WillReturn.Add("6 7");
WillReturn.Add("6 8");
WillReturn.Add("7 8");
WillReturn.Add("8 9");
WillReturn.Add("3");
WillReturn.Add("0 1");
WillReturn.Add("5 9");
WillReturn.Add("1 3");
//yes
//yes
//no
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
// 隣接リスト
static Dictionary<int, List<int>> mToNodeListDict = new Dictionary<int, List<int>>();
static int mN;
static int mM;
static void Main()
{
List<string> InputList = GetInputList();
int[] wkArr = { };
Action<string> SplitAct = pStr =>
wkArr = pStr.Split(' ').Select(X => int.Parse(X)).ToArray();
SplitAct(InputList[0]);
mN = wkArr[0];
mM = wkArr[1];
foreach (string EachStr in InputList.Skip(1).Take(mM)) {
SplitAct(EachStr);
int FromNode = wkArr[0];
int ToNode = wkArr[1];
if (mToNodeListDict.ContainsKey(FromNode) == false) {
mToNodeListDict[FromNode] = new List<int>();
}
if (mToNodeListDict.ContainsKey(ToNode) == false) {
mToNodeListDict[ToNode] = new List<int>();
}
mToNodeListDict[FromNode].Add(ToNode);
mToNodeListDict[ToNode].Add(FromNode);
}
ExecDFS(0, mN - 1);
foreach (string EachStr in InputList.Skip(1 + mM + 1)) {
SplitAct(EachStr);
int FromNode = wkArr[0];
int ToNode = wkArr[1];
if (mTreeDict[FromNode] == mTreeDict[ToNode]) {
Console.WriteLine("yes");
}
else {
Console.WriteLine("no");
}
}
}
// 代表ノード[ノード]なDict
static Dictionary<int, int> mTreeDict = new Dictionary<int, int>();
struct JyoutaiDef
{
internal int CurrNode;
}
// 深さ優先探索を行う
static void ExecDFS(int pMinNode, int pMaxNode)
{
for (int I = pMinNode; I <= pMaxNode; I++) {
if (mTreeDict.ContainsKey(I)) continue;
var Stk = new Stack<JyoutaiDef>();
JyoutaiDef WillPush;
WillPush.CurrNode = I;
Stk.Push(WillPush);
mTreeDict[I] = I;
while (Stk.Count > 0) {
JyoutaiDef Popped = Stk.Pop();
// 子ノード無しの場合
if (mToNodeListDict.ContainsKey(Popped.CurrNode) == false)
continue;
foreach (int EachToNode in mToNodeListDict[Popped.CurrNode]) {
if (mTreeDict.ContainsKey(EachToNode)) continue;
WillPush.CurrNode = EachToNode;
Stk.Push(WillPush);
mTreeDict[EachToNode] = I;
}
}
}
}
}
解説
最初に、深さ優先探索の根ノードで分類してます。
それから、各クエリに回答してます。