Advertisement
HashZayed

Journey To Moon

May 19th, 2018
111
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.97 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. class Solution {
  6. static void PrintRoots(int[] keys, int size){
  7. Console.WriteLine();
  8. Console.Write("Keys: ");
  9. for(int i = 0;i<size;i++){
  10. Console.Write(keys[i]+",");
  11. }
  12. Console.WriteLine();
  13. }
  14. static void PrintCountries(Dictionary<int,HashSet<int>> allCountries){
  15. Console.WriteLine("Countries: ");
  16. foreach(int key in allCountries.Keys){
  17. foreach(var key2 in allCountries[key]){
  18. Console.Write(key2+",");
  19. }
  20. Console.WriteLine();
  21. }
  22. Console.WriteLine();
  23. }
  24. static Int64 journeyToMoon(int n, int[][] astronaut) {
  25. // Complete this function
  26. Dictionary<int,HashSet<int>> allCountries = new Dictionary<int,HashSet<int>>();
  27. int[] roots = new int[n];
  28. Int64 totalCombinations = 0;
  29.  
  30. for(int i = 0;i<n;i++){
  31. HashSet<int> tempSet = new HashSet<int>();
  32. tempSet.Add(i);
  33. allCountries.Add(i,tempSet);
  34. roots[i]=i;
  35. }
  36. for(int i=0;i<astronaut.Length;i++){
  37. int lesser,greater;
  38.  
  39. if(astronaut[i][0]<astronaut[i][1]){
  40. lesser = astronaut[i][0];
  41. greater = astronaut[i][1];
  42. }else{
  43. lesser = astronaut[i][1];
  44. greater = astronaut[i][0];
  45. }
  46.  
  47. if(!allCountries.ContainsKey(lesser)) lesser = roots[lesser];
  48. if(!allCountries.ContainsKey(greater)) greater = roots[greater];
  49.  
  50. allCountries[roots[lesser]].UnionWith(allCountries[roots[greater]]);
  51. foreach(int key in allCountries[greater]){
  52. roots[key] = roots[lesser];
  53. }
  54. if(roots[greater]!=greater) allCountries.Remove(greater);
  55. //PrintRoots(roots,n);
  56. //PrintCountries(allCountries);
  57. }
  58.  
  59. Int64 prevTotal = 0;
  60. foreach(var key in allCountries.Keys){
  61. if(prevTotal == 0){
  62. prevTotal = allCountries[key].Count;
  63. }else{
  64. totalCombinations+=(allCountries[key].Count*prevTotal);
  65. prevTotal += allCountries[key].Count;
  66. }
  67. }
  68.  
  69. return totalCombinations;
  70. }
  71.  
  72. static void Main(String[] args) {
  73. string[] tokens_n = Console.ReadLine().Split(' ');
  74. int n = Convert.ToInt32(tokens_n[0]);
  75. int p = Convert.ToInt32(tokens_n[1]);
  76. int[][] astronaut = new int[p][];
  77. for(int astronaut_i = 0; astronaut_i < p; astronaut_i++){
  78. string[] astronaut_temp = Console.ReadLine().Split(' ');
  79. astronaut[astronaut_i] = Array.ConvertAll(astronaut_temp,Int32.Parse);
  80. }
  81. Int64 result = journeyToMoon(n, astronaut);
  82. Console.WriteLine(result);
  83. }
  84. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement