AtCoderのABC
次のABCの問題へ
前のABCの問題へ
ABC138-D Ki
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 3");
WillReturn.Add("1 2");
WillReturn.Add("2 3");
WillReturn.Add("2 4");
WillReturn.Add("2 10");
WillReturn.Add("1 100");
WillReturn.Add("3 1");
//100 110 111 110
}
else if (InputPattern == "Input2") {
WillReturn.Add("6 2");
WillReturn.Add("1 2");
WillReturn.Add("1 3");
WillReturn.Add("2 4");
WillReturn.Add("3 6");
WillReturn.Add("2 5");
WillReturn.Add("1 10");
WillReturn.Add("1 10");
//20 20 20 20 20 20
}
else {
string wkStr;
while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
}
return WillReturn;
}
struct JyoutaiDef
{
internal int CurrNode;
internal int SumVal;
}
// 隣接リスト
static Dictionary<int, List<int>> mToNodeListDict = new Dictionary<int, List<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];
int Q = wkArr[1];
foreach (string EachStr in InputList.Skip(1).Take(N - 1)) {
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);
}
int[] ValArr = new int[N + 1];
foreach (string EachStr in InputList.Skip(N)) {
SplitAct(EachStr);
ValArr[wkArr[0]] += wkArr[1];
}
var Stk = new Stack<JyoutaiDef>();
JyoutaiDef WillPush;
WillPush.CurrNode = 1;
WillPush.SumVal = ValArr[1];
Stk.Push(WillPush);
var VisitedSet = new HashSet<int>();
VisitedSet.Add(1);
var PoppedList = new List<JyoutaiDef>();
while (Stk.Count > 0) {
JyoutaiDef Popped = Stk.Pop();
PoppedList.Add(Popped);
// 子ノード無しの場合
if (mToNodeListDict.ContainsKey(Popped.CurrNode) == false)
continue;
foreach (int EachToNode in mToNodeListDict[Popped.CurrNode]) {
if (VisitedSet.Add(EachToNode)) {
WillPush.CurrNode = EachToNode;
WillPush.SumVal = Popped.SumVal + ValArr[EachToNode];
Stk.Push(WillPush);
}
}
}
var Query = PoppedList.OrderBy(pX => pX.CurrNode);
var WillOutIntList = new List<int>();
foreach (var EachItem in Query) {
WillOutIntList.Add(EachItem.SumVal);
}
string[] WillOutStrArr = Array.ConvertAll(WillOutIntList.ToArray(), pX => pX.ToString());
Console.WriteLine(string.Join(" ", WillOutStrArr));
}
}
解説
各ノードにカウンターの値を足しておいてから、
根からの深さ優先探索を行い、累積和を求めるようにしてます。