Program.cs 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. namespace D8._2
  5. {
  6. class Program
  7. {
  8. static void Main(string[] args)
  9. {
  10. if (args.Length < 1) return;
  11. if (File.Exists(args[0]) == false) return;
  12. var file = File.OpenText(args[0]);
  13. var text = file.ReadToEnd();
  14. var all = new List<string>(text.Split(" "));
  15. var root = getNode(all);
  16. Console.WriteLine($"Result is : {root.Value}");
  17. }
  18. static Node getNode(List<string> all)
  19. {
  20. var node = new Node();
  21. (int children, int metadatas) header = (int.Parse(all[0]), int.Parse(all[1]));
  22. all.RemoveAt(0);
  23. all.RemoveAt(0);
  24. for (int j = 0; j < header.children; j++)
  25. {
  26. var childnode = getNode(all);
  27. node.Children.Add(childnode);
  28. }
  29. int metasum = 0;
  30. for (int j = 0; j < header.metadatas; j++)
  31. {
  32. int meta = int.Parse(all[0]);
  33. all.RemoveAt(0);
  34. node.Meta.Add(meta);
  35. if (header.children == 0) metasum += meta;
  36. else
  37. {
  38. var i = meta - 1;
  39. if (i < 0 || i >= node.Children.Count) continue;
  40. metasum += node.Children[i].Value;
  41. }
  42. }
  43. node.Value = metasum;
  44. return node;
  45. }
  46. }
  47. class Node
  48. {
  49. public List<int> Meta { get; set; }
  50. public List<Node> Children { get; set; }
  51. public int Value { get; set; }
  52. public Node()
  53. {
  54. Meta = new List<int>();
  55. Children = new List<Node>();
  56. }
  57. }
  58. }