AtCoderのABC    次のABCの問題へ    前のABCの問題へ

ABC482-E Diameter Endpoint Colors


問題へのリンク


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("1 2");
            WillReturn.Add("2 3");
            WillReturn.Add("2 4");
            WillReturn.Add("4 5");
            WillReturn.Add("2 1 3 1 2");
            //1
        }
        else if (InputPattern == "Input2") {
            WillReturn.Add("8");
            WillReturn.Add("3 2");
            WillReturn.Add("5 8");
            WillReturn.Add("2 7");
            WillReturn.Add("8 1");
            WillReturn.Add("2 8");
            WillReturn.Add("1 4");
            WillReturn.Add("6 5");
            WillReturn.Add("2 1 5 2 6 5 2 5");
            //2
        }
        else if (InputPattern == "Input3") {
            WillReturn.Add("9");
            WillReturn.Add("2 3");
            WillReturn.Add("4 8");
            WillReturn.Add("6 1");
            WillReturn.Add("3 6");
            WillReturn.Add("1 9");
            WillReturn.Add("8 6");
            WillReturn.Add("2 5");
            WillReturn.Add("7 2");
            WillReturn.Add("3 2 1 3 3 4 2 3 3");
            //2
        }
        else {
            string wkStr;
            while ((wkStr = Console.ReadLine()) != null) WillReturn.Add(wkStr);
        }
        return WillReturn;
    }

    static long[] GetSplitArr(string pStr)
    {
        return (pStr == "" ? new string[0] : pStr.Split(' ')).Select(pX => long.Parse(pX)).ToArray();
    }

    // 隣接リスト
    static Dictionary<long, List<long>> mToNodeListDict = new Dictionary<long, List<long>>();

    static void Main()
    {
        List<string> InputList = GetInputList();
        long N = long.Parse(InputList[0]);

        long[] wkArr = { };
        Action<string> SplitAct = (pStr) => wkArr = GetSplitArr(pStr);

        foreach (string EachStr in InputList.Skip(1).Take((int)N - 1)) {
            SplitAct(EachStr);
            long FromNode = wkArr[0];
            long ToNode = wkArr[1];

            if (mToNodeListDict.ContainsKey(FromNode) == false) {
                mToNodeListDict[FromNode] = new List<long>();
            }
            if (mToNodeListDict.ContainsKey(ToNode) == false) {
                mToNodeListDict[ToNode] = new List<long>();
            }
            mToNodeListDict[FromNode].Add(ToNode);
            mToNodeListDict[ToNode].Add(FromNode);
        }

        long[] ColorArr = GetSplitArr(InputList.Last());

        long Diameter, Leaf1, Leaf2;
        List<long> CenterNodeList;
        ClassTreeDiameter.DeriveTreeDiameter(1, mToNodeListDict,
            out Diameter, out Leaf1, out Leaf2, out CenterNodeList);

        // 木の中心が1ノードの場合
        if (CenterNodeList.Count == 1) {
            List<JyoutaiDef> ResultList = ExecDFS(CenterNodeList[0]);

            long MaxLevel = ResultList.Max(pX => pX.Level);
            ResultList.RemoveAll(pX => pX.Level < MaxLevel);

            // 件数[色]なDict
            var LeafCntDict = new Dictionary<long, long>();

            // 件数[{色,レベル2ノード}]なDict
            var PairCntDict = new Dictionary<string, long>();

            foreach (JyoutaiDef EachJyoutai in ResultList) {
                long CurrColor = ColorArr[EachJyoutai.CurrNode - 1];
                if (LeafCntDict.ContainsKey(CurrColor) == false) {
                    LeafCntDict[CurrColor] = 0;
                }
                LeafCntDict[CurrColor]++;

                string Pair = string.Format("{0},{1}", CurrColor, EachJyoutai.Node_Level2);
                if (PairCntDict.ContainsKey(Pair) == false) {
                    PairCntDict[Pair] = 0;
                }
                PairCntDict[Pair]++;
            }

            long Answer = 0;
            foreach (var EachPair in PairCntDict) {
                string[] SplitArr = EachPair.Key.Split(',');
                long Color = long.Parse(SplitArr[0]);
                Answer += EachPair.Value * (LeafCntDict[Color] - EachPair.Value);
            }
            Console.WriteLine(Answer / 2); // 組合せなので2で割る
        }
        else {
            // 木の中心が2ノードの場合
            List<JyoutaiDef> ResultList0 = ExecDFS(CenterNodeList[0]);
            if (ResultList0.Count == 0) {
                Console.WriteLine(0); return;
            }
            long MaxLevel0 = ResultList0.Max(pX => pX.Level);
            ResultList0.RemoveAll(pX => pX.Level < MaxLevel0);

            List<JyoutaiDef> ResultList1 = ExecDFS(CenterNodeList[1]);
            if (ResultList1.Count == 0) {
                Console.WriteLine(0); return;
            }
            long MaxLevel1 = ResultList1.Max(pX => pX.Level);
            ResultList1.RemoveAll(pX => pX.Level < MaxLevel1);

            // 件数[色]
            var CntDict0 = new Dictionary<long, long>();
            foreach (JyoutaiDef EachJyoutai in ResultList0) {
                long CurrColor = ColorArr[EachJyoutai.CurrNode - 1];
                if (CntDict0.ContainsKey(CurrColor) == false) {
                    CntDict0[CurrColor] = 0;
                }
                CntDict0[CurrColor]++;
            }

            // 件数[色]
            var CntDict1 = new Dictionary<long, long>();
            foreach (JyoutaiDef EachJyoutai in ResultList1) {
                long CurrColor = ColorArr[EachJyoutai.CurrNode - 1];
                if (CntDict1.ContainsKey(CurrColor) == false) {
                    CntDict1[CurrColor] = 0;
                }
                CntDict1[CurrColor]++;
            }

            long Answer = 0;
            foreach (var EachPair in CntDict0) {
                if (CntDict1.ContainsKey(EachPair.Key)) {
                    Answer += EachPair.Value * CntDict1[EachPair.Key];
                }
            }
            Console.WriteLine(Answer); // 順序違いを集計してないので、2で割るのは不要
        }
    }

    static List<JyoutaiDef> ExecDFS(long pRootNode)
    {
        var ResultList = new List<JyoutaiDef>();

        var Stk = new Stack<JyoutaiDef>();
        JyoutaiDef WillPush;
        WillPush.CurrNode = pRootNode;
        WillPush.Node_Level2 = -1;
        WillPush.Level = 1;
        Stk.Push(WillPush);

        var VisitedSet = new HashSet<long>();
        VisitedSet.Add(pRootNode);
        while (Stk.Count > 0) {
            JyoutaiDef Popped = Stk.Pop();
            ResultList.Add(Popped);

            foreach (long EachToNode in mToNodeListDict[Popped.CurrNode]) {
                if (VisitedSet.Add(EachToNode)) {
                    WillPush.CurrNode = EachToNode;
                    WillPush.Level = Popped.Level + 1;
                    if (WillPush.Level == 2) {
                        WillPush.Node_Level2 = EachToNode;
                    }
                    else {
                        WillPush.Node_Level2 = Popped.Node_Level2;
                    }
                    Stk.Push(WillPush);
                }
            }
        }
        return ResultList;
    }

    struct JyoutaiDef
    {
        internal long CurrNode;
        internal long Node_Level2; // レベル2のノード
        internal long Level;
    }
}

#region ClassTreeDiameter
// 根付き木の直径を求めるクラス
internal class ClassTreeDiameter
{
    // {ルートノード,連結リスト}を引数とし、
    // {木の直径、葉ノード1、葉ノード2、木の中心のノードのList}を設定
    static internal void DeriveTreeDiameter(
        long pRootNode, Dictionary<long, List<long>> pToNodeListDict,
        out long pDiameter, out long pLeaf1, out long pLeaf2,
        out List<long> pCenterNodeList)
    {
        // ===============================================================
        // double sweepのアルゴリズム
        // ===============================================================

        // 根ノードからの距離[ノード]なDict
        var DistanceDictRoot = ExecDFS(1, pToNodeListDict);
        pLeaf1 = DistanceDictRoot.OrderByDescending(pX => pX.Value).First().Key;

        // 葉ノード1からの距離[ノード]なDict
        var DistanceDictLeaf1 = ExecDFS(pLeaf1, pToNodeListDict);
        pLeaf2 = DistanceDictLeaf1.OrderByDescending(pX => pX.Value).First().Key;

        pDiameter = DistanceDictLeaf1.Values.Max();

        pCenterNodeList = new List<long>();

        // 葉ノード2からの距離[ノード]なDict
        var DistanceDictLeaf2 = ExecDFS(pLeaf2, pToNodeListDict);

        var OKDistanceSet = new HashSet<long>();
        OKDistanceSet.Add(pDiameter / 2);
        if (pDiameter % 2 == 1) {
            OKDistanceSet.Add(pDiameter / 2 + 1);
        }

        var CenterNodeSet1 = new HashSet<long>();
        foreach (var EachPair in DistanceDictLeaf1) {
            if (OKDistanceSet.Contains(EachPair.Value)) {
                CenterNodeSet1.Add(EachPair.Key);
            }
        }

        var CenterNodeSet2 = new HashSet<long>();
        foreach (var EachPair in DistanceDictLeaf2) {
            if (OKDistanceSet.Contains(EachPair.Value)) {
                CenterNodeSet2.Add(EachPair.Key);
            }
        }

        CenterNodeSet1.IntersectWith(CenterNodeSet2);
        pCenterNodeList.AddRange(CenterNodeSet1);
    }

    // 根ノードを引数としてDFSを行う
    static private Dictionary<long, long>
        ExecDFS(long pRootNode, Dictionary<long, List<long>> pToNodeListDict)
    {
        var DistanceDict = new Dictionary<long, long>();

        var Stk = new Stack<JyoutaiDefTreeDiameter>();
        JyoutaiDefTreeDiameter WillPush;
        WillPush.CurrNode = pRootNode;
        WillPush.Distance = 0; // 距離なので0始まり
        Stk.Push(WillPush);

        var VisitedSet = new HashSet<long>();
        VisitedSet.Add(pRootNode);
        while (Stk.Count > 0) {
            JyoutaiDefTreeDiameter Popped = Stk.Pop();

            DistanceDict[Popped.CurrNode] = Popped.Distance;

            foreach (long EachToNode in pToNodeListDict[Popped.CurrNode]) {
                if (VisitedSet.Add(EachToNode)) {
                    WillPush.CurrNode = EachToNode;
                    WillPush.Distance = Popped.Distance + 1;
                    Stk.Push(WillPush);
                }
            }
        }
        return DistanceDict;
    }

    private struct JyoutaiDefTreeDiameter
    {
        internal long CurrNode;
        internal long Distance;
    }
}
#endregion


解説

まず、
第20回PAST L 直径のペア
の類題として、木の中心を求めます。

木の中心が、1ノードか2ノードかで場合分けして考えます。

●場合1 木の中心が1ノード
木の中心ノードからDFSし、レベル2のノードを覚えつつ
葉ノードの情報を集めます。

葉ノードの集計を行い。
件数[色]なDict
件数[{色,レベル2ノード}]なDict
を用意すれば、直系の両端の葉ノードのペア数を求めることができます。

●場合2 木の中心が2ノード
木の中心である2つのノードからDFSし、
件数[色]なDictを用意し、
同色での組合せ数を求めれば、
直系の両端の葉ノードのペア数を求めることができます。