AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC302-E Isolation
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("3 7");
WillReturn.Add("1 1 2");
WillReturn.Add("1 1 3");
WillReturn.Add("1 2 3");
WillReturn.Add("2 1");
WillReturn.Add("1 1 2");
WillReturn.Add("2 2");
WillReturn.Add("1 1 2");
//1
//0
//0
//1
//0
//3
//1
}
else if (InputPattern == "Input2") {
WillReturn.Add("2 1");
WillReturn.Add("2 1");
//2
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
// 隣接リスト
static Dictionary<int, HashSet<int>> mToNodeListDict = new Dictionary<int, HashSet<int>>();
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];
foreach (string EachStr in InputList.Skip(1)) {
SplitAct(EachStr);
int Type = wkArr[0];
if (Type == 1) {
int FromNode = wkArr[1];
int ToNode = wkArr[2];
if (mToNodeListDict.ContainsKey(FromNode) == false) {
mToNodeListDict[FromNode] = new HashSet<int>();
}
mToNodeListDict[FromNode].Add(ToNode);
if (mToNodeListDict.ContainsKey(ToNode) == false) {
mToNodeListDict[ToNode] = new HashSet<int>();
}
mToNodeListDict[ToNode].Add(FromNode);
}
if (Type == 2) {
int CurrNode = wkArr[1];
if (mToNodeListDict.ContainsKey(CurrNode)) {
var DelKouho = new List<int>();
foreach (int EachNode in mToNodeListDict[CurrNode]) {
if (mToNodeListDict.ContainsKey(EachNode)) {
mToNodeListDict[EachNode].Remove(CurrNode);
DelKouho.Add(EachNode);
}
}
foreach (int Each in DelKouho) {
if (mToNodeListDict[Each].Count == 0) {
mToNodeListDict.Remove(Each);
}
}
}
mToNodeListDict.Remove(CurrNode);
}
Console.WriteLine(N - mToNodeListDict.Count);
}
}
}
解説
クエリ2では、クエリ1で追加した辺しか削除しないので、
隣接リストをHashSetで管理すれば、間に合います。