using System; using System.Collections.Generic; using System.IO; using System.Linq; namespace D7._1 { class Program { static void Main(string[] args) { if (args.Length < 1) return; if (File.Exists(args[0]) == false) return; var file = File.OpenText(args[0]); var builder = new Dictionary(); do { var line = file.ReadLine(); if (line == null) break; AddDependency(builder, line); } while (true); string path = GetPath(builder); Console.WriteLine(path); } private static string GetPath(Dictionary builder) { List possibleValues = builder.Select(s => s.Value).ToList(); string path = ""; while (possibleValues.Count() > 0) { var first = possibleValues .OrderBy(c => c.Name) .FirstOrDefault(c => c.Dependencies.Count == 0); path += first.Name; RemoveDependency(possibleValues, first); } return path; } private static void RemoveDependency(List possibleValues, Node first) { possibleValues.Remove(first); foreach (var next in possibleValues) next.Dependencies.Remove(first); } private static void AddDependency(Dictionary builder, string line) { var left = line.Substring(5, 1)[0]; var right = line.Substring(36, 1)[0]; if (builder.ContainsKey(left) == false) builder.Add(left, new Node { Name = left, Dependencies = new List() }); if (builder.ContainsKey(right) == false) builder.Add(right, new Node { Name = right, Dependencies = new List() }); var nleft = builder[left]; var nright = builder[right]; nright.Dependencies.Add(nleft); } public class Node { public char Name { get; set; } public List Dependencies { get; set; } public override int GetHashCode() { return Name.GetHashCode(); } public override bool Equals(object obj) { var o = obj as Node; return Name.Equals(o.Name); } } } }