zh_stoqnov

LongestPathInTree

Aug 12th, 2015
343
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.64 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4.  
  5. namespace _4.Longest_Path_in_a_Tree
  6. {
  7. class LongestPathInTree
  8. {
  9. static void Main()
  10. {
  11. int n = int.Parse(Console.ReadLine());
  12. int m = int.Parse(Console.ReadLine());
  13. Dictionary<int, List<int>> parentChildrens =
  14. new Dictionary<int, List<int>>();
  15. Dictionary<int, int?> parents =
  16. new Dictionary<int, int?>();
  17.  
  18. for (int i = 0; i < m; i++)
  19. {
  20. var nums = Console.ReadLine().Split(' ')
  21. .Select(int.Parse)
  22. .ToList();
  23. int first = nums[0];
  24. int second = nums[1];
  25.  
  26. if (!parentChildrens.ContainsKey(first))
  27. {
  28. parentChildrens[first] = new List<int>();
  29. }
  30.  
  31. if (!parentChildrens.ContainsKey(second))
  32. {
  33. parentChildrens[second] = new List<int>();
  34. }
  35.  
  36. if (!parents.ContainsKey(second))
  37. {
  38. parents[second] = first;
  39. }
  40.  
  41. if (!parents.ContainsKey(first))
  42. {
  43. parents[first] = null;
  44. }
  45.  
  46. parentChildrens[first].Add(second);
  47. parents[second] = first;
  48. }
  49.  
  50. var leaves = parentChildrens
  51. .Where(p => p.Value.Count == 0)
  52. .Select(p => p.Key)
  53. .ToList();
  54.  
  55. var root = parents
  56. .First(p => p.Value == null)
  57. .Key;
  58. var pathsToRootList = new List<List<int>>();
  59.  
  60. foreach (var leaf in leaves)
  61. {
  62. int currNode = leaf;
  63. List<int> currentPath = new List<int>();
  64. while (currNode != root)
  65. {
  66. currentPath.Add(currNode);
  67. currNode = (int)parents[currNode];
  68. }
  69. pathsToRootList.Add(currentPath);
  70. }
  71.  
  72. int maxSum = 0;
  73.  
  74. for (int i = 0; i < pathsToRootList.Count; i++)
  75. {
  76. maxSum = pathsToRootList.Where((t, j) => i != j &&
  77. !pathsToRootList[i].Intersect(t).Any())
  78. .Select(t => pathsToRootList[i].Sum() + t.Sum() + root)
  79. .Concat(new[] {maxSum})
  80. .Max();
  81. }
  82.  
  83. Console.WriteLine();
  84. Console.WriteLine(maxSum);
  85. }
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment