Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- class Solution {
- static void PrintRoots(int[] keys, int size){
- Console.WriteLine();
- Console.Write("Keys: ");
- for(int i = 0;i<size;i++){
- Console.Write(keys[i]+",");
- }
- Console.WriteLine();
- }
- static void PrintCountries(Dictionary<int,HashSet<int>> allCountries){
- Console.WriteLine("Countries: ");
- foreach(int key in allCountries.Keys){
- foreach(var key2 in allCountries[key]){
- Console.Write(key2+",");
- }
- Console.WriteLine();
- }
- Console.WriteLine();
- }
- static Int64 journeyToMoon(int n, int[][] astronaut) {
- // Complete this function
- Dictionary<int,HashSet<int>> allCountries = new Dictionary<int,HashSet<int>>();
- int[] roots = new int[n];
- Int64 totalCombinations = 0;
- for(int i = 0;i<n;i++){
- HashSet<int> tempSet = new HashSet<int>();
- tempSet.Add(i);
- allCountries.Add(i,tempSet);
- roots[i]=i;
- }
- for(int i=0;i<astronaut.Length;i++){
- int lesser,greater;
- if(astronaut[i][0]<astronaut[i][1]){
- lesser = astronaut[i][0];
- greater = astronaut[i][1];
- }else{
- lesser = astronaut[i][1];
- greater = astronaut[i][0];
- }
- if(!allCountries.ContainsKey(lesser)) lesser = roots[lesser];
- if(!allCountries.ContainsKey(greater)) greater = roots[greater];
- allCountries[roots[lesser]].UnionWith(allCountries[roots[greater]]);
- foreach(int key in allCountries[greater]){
- roots[key] = roots[lesser];
- }
- if(roots[greater]!=greater) allCountries.Remove(greater);
- //PrintRoots(roots,n);
- //PrintCountries(allCountries);
- }
- Int64 prevTotal = 0;
- foreach(var key in allCountries.Keys){
- if(prevTotal == 0){
- prevTotal = allCountries[key].Count;
- }else{
- totalCombinations+=(allCountries[key].Count*prevTotal);
- prevTotal += allCountries[key].Count;
- }
- }
- return totalCombinations;
- }
- static void Main(String[] args) {
- string[] tokens_n = Console.ReadLine().Split(' ');
- int n = Convert.ToInt32(tokens_n[0]);
- int p = Convert.ToInt32(tokens_n[1]);
- int[][] astronaut = new int[p][];
- for(int astronaut_i = 0; astronaut_i < p; astronaut_i++){
- string[] astronaut_temp = Console.ReadLine().Split(' ');
- astronaut[astronaut_i] = Array.ConvertAll(astronaut_temp,Int32.Parse);
- }
- Int64 result = journeyToMoon(n, astronaut);
- Console.WriteLine(result);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement