public static IList <string> Answer(IList <string> inputs) { var chars = new[] { ' ' }; var line0 = inputs[0].Split(chars); var verticeCount = int.Parse(line0[0]); var edgeCount = int.Parse(line0[1]); var xs = Enumerable.Range(1, edgeCount) .Select(i => { var items = inputs[i].Trim().Split(chars, StringSplitOptions.RemoveEmptyEntries); return(new { Left = GetIndex(items[0]), Right = GetIndex(items[1]) }); }); var graph = new AdjacencyListGraph(verticeCount); foreach (var x in xs) { graph.AddDirectedEdge(x.Left, x.Right); } //Console.WriteLine(graph); var s = new TopologicalSort(graph); s.Search(); var answer = string.Join(" ", s.Order.Select(GetSource)); return(new[] { answer }); }
private static bool IsCyclic(AdjacencyListGraph <long> g) { try { new DepthFirstSearchWithCycleDetection(g).Search(); return(false); } catch (GraphCycleException) { return(true); } }
public static IEnumerable <int> StronglyConnectedComponents(AdjacencyListGraph <long> graph, AdjacencyListGraph <long> reverse) { //run dfs of reverse graph var srg = new TopologicalSort(reverse); srg.Search(); //look for v in graph in reverse post order var sg = new DepthFirstSearchWithComponents(graph); var order = srg.Order; foreach (var v in order) { //if not visited => explore and mark visted vertices as new component sg.Explore(v); } return(sg.Components); }
public static IList <string> Answer(IList <string> inputs) { var chars = new[] { ' ' }; var line0 = inputs[0].Split(chars); var verticeCount = int.Parse(line0[0]); var edgeCount = int.Parse(line0[1]); var xs = Enumerable.Range(1, edgeCount) .Select(i => { var items = inputs[i].Trim().Split(chars, StringSplitOptions.RemoveEmptyEntries); return(new { Left = GetIndex(items[0]), Right = GetIndex(items[1]) }); }); var g = new AdjacencyListGraph(verticeCount); var rg = new AdjacencyListGraph(verticeCount); foreach (var x in xs) { g.AddDirectedEdge(x.Left, x.Right); rg.AddDirectedEdge(x.Right, x.Left); } //Console.WriteLine(g); //Console.WriteLine(rg); var s = StronglyConnectedComponents(g, rg); var answer = s.Count(); return(new[] { answer.ToString() }); }