AtCoderのPAST    次のPASTの問題へ    前のPASTの問題へ

第7回PAST J 終わりなき旅


問題へのリンク


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

    // 頂点の数
    static long mN;

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

    static void Main()
    {
        List<string> InputList = GetInputList();

        long[] wkArr = { };
        Action<string> SplitAct = pStr =>
            wkArr = pStr.Split(' ').Select(pX => long.Parse(pX)).ToArray();

        SplitAct(InputList[0]);
        mN = wkArr[0];

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

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

        if (DirectedGraphHasCycle_Class.HasCycle(1, mN, mToNodeListDict)) {
            Console.WriteLine("Yes");
        }
        else {
            Console.WriteLine("No");
        }
    }
}

#region DirectedGraphHasCycle_Class
// 有向グラフの閉路有無の判定クラス
internal class DirectedGraphHasCycle_Class
{
    private static long mMinNode;
    private static long mMaxNode;
    private static Dictionary<long, List<long>> mToNodeListDict;

    private static long[] mDegreeArr;
    private static HashSet<long> mVisitedSet;

    // 最小のノードID,最大のノードID,隣接グラフを引数とし、閉路の有無を返す
    internal static bool HasCycle(long pMinNode, long pMaxNode,
        Dictionary<long, List<long>> pToNodeListDict)
    {
        mMinNode = pMinNode;
        mMaxNode = pMaxNode;
        mToNodeListDict = pToNodeListDict;
        mVisitedSet = new HashSet<long>();

        // 入次数を配列で管理
        mDegreeArr = new long[mMaxNode + 1];
        foreach (var EachPair in mToNodeListDict) {
            foreach (long EachToNode in EachPair.Value) {
                mDegreeArr[EachToNode]++;
            }
        }

        // 入次数が0で、未訪問ノードから深さ優先探索
        for (long I = mMinNode; I <= mMaxNode; I++) {
            if (mDegreeArr[I] > 0) continue;
            if (mVisitedSet.Contains(I)) continue;

            HasCycleHelperExecDFS(I);
        }

        long NodeCnt = pMaxNode - pMinNode + 1;
        return NodeCnt > mVisitedSet.Count;
    }

    // HasCycleのヘルパメソッドで、深さ優先探索を行う
    private struct JyoutaiDef_HasCycle
    {
        internal long CurrNode;
    }
    private static void HasCycleHelperExecDFS(long pStaNode)
    {
        JyoutaiDef_HasCycle WillPush;
        WillPush.CurrNode = pStaNode;

        var Stk = new Stack<JyoutaiDef_HasCycle>();
        Stk.Push(WillPush);
        while (Stk.Count > 0) {
            JyoutaiDef_HasCycle Popped = Stk.Pop();

            long CurrNode = Popped.CurrNode;
            mVisitedSet.Add(CurrNode);

            if (mToNodeListDict.ContainsKey(CurrNode) == false) {
                continue;
            }
            foreach (int EachToNode in mToNodeListDict[CurrNode]) {
                // 入次数はデクリメント
                mDegreeArr[EachToNode]--;

                // 入次数が0でなかったら訪問しない
                if (mDegreeArr[EachToNode] > 0) continue;

                // 再訪防止
                if (mVisitedSet.Add(EachToNode) == false) continue;

                WillPush.CurrNode = EachToNode;
                Stk.Push(WillPush);
            }
        }
    }
}
#endregion


解説

有向グラフでCycleがないこと ⇔ トポロジカルソート可能なこと
なので、DFSでトポロジカルソートし、
トポロジカルソートの結果でCycleの有無を判定してます。