public static void Part2() { //The bridge you've built isn't long enough; you can't jump the rest of the way. //In the example above, there are two longest bridges: // 0 / 2--2 / 2--2 / 3--3 / 4 // 0 / 2--2 / 2--2 / 3--3 / 5 //Of them, the one which uses the 3 / 5 component is stronger; its strength is 0 + 2 + 2 + 2 + 2 + 3 // + 3 + 5 = 19. //What is the strength of the longest bridge you can make? If you can make multiple bridges of the //longest length, pick the strongest one. IList <Node2> components = new List <Node2>(); int maxStrengthLongest = 0; int longestBridge = 0; string line; using (StringReader reader = new StringReader(Input)) { while ((line = reader.ReadLine()) != null) { var component = line.Split('/').Select(p => int.Parse(p)); components.Add(new Node2 { A = component.First(), B = component.Last() }); } } var roots = components.Where(c => c.A == 0 || c.B == 0); foreach (Node2 rootNode in roots) { Node2 root = new Node2 { A = rootNode.A == 0 ? rootNode.A : rootNode.B, B = rootNode.A == 0 ? rootNode.B : rootNode.A, }; root.AddChildren(ref components, ref maxStrengthLongest, ref longestBridge); } Debug.WriteLine("Max length: " + longestBridge); Debug.WriteLine("Max strength: " + maxStrengthLongest); }
public void AddChildren(ref IList <Node2> components, ref int maxStrength, ref int maxLength) { foreach (Node2 component in components.Where(c => !InChain(c))) { if (component.A == B) { var node = new Node2 { A = component.A, B = component.B, Parent = this }; Children.Add(node); if (node.Length > maxLength) { maxLength = node.Length; maxStrength = node.Strength; } if (node.Length == maxStrength && node.Strength > maxStrength) { maxStrength = node.Length; } node.AddChildren(ref components, ref maxStrength, ref maxLength); } if (component.B == B) { var node = new Node2 { A = component.B, B = component.A, Parent = this }; Children.Add(node); if (node.Length > maxLength) { maxLength = node.Length; maxStrength = node.Strength; } if (node.Length == maxStrength && node.Strength > maxStrength) { maxStrength = node.Length; } node.AddChildren(ref components, ref maxStrength, ref maxLength); } } }