using System; using System.Collections.Generic; namespace ConsoleApp2 { class Program { static void Main(string[] args) { Solution sol = new Solution(); Console.WriteLine(sol.solution(5, new int[,] { { 0,1,1 }, { 3,4,1 }, { 1,2,2}, { 2,3,4 }})); } } public class Solution { public class Node : IComparable { public int cur; public int next; public int dis; public Node(int cur, int next, int dis) { this.cur = cur; this.next = next; this.dis = dis; } public int CompareTo(Node other) { if (dis < other.dis) { return -1; } else if (dis > other.dis) { return 1; } else return 0; } } public int GetParent(int[] table, int adr) { if (table[adr] == adr) return adr; return table[adr] = GetParent(table, table[adr]); } public void SetParent(int[] table,int a, int b) { a = GetParent(table, a); b = GetParent(table, b); int min = Math.Min(a, b); table[a] = table[b] = min; } public int solution(int n, int[,] costs) { int answer = 0; int[] table = new int[n]; List nodeList = new List(); for (int i = 0; i < n; i++) { table[i] = i; } for (int i = 0; i < costs.GetLength(0); i++) { nodeList.Add(new Node(costs[i, 0], costs[i, 1], costs[i, 2])); } nodeList.Sort(); for (int i = 0; i < nodeList.Count; i++) { if (table[nodeList[i].cur] != table[nodeList[i].next]) { answer += nodeList[i].dis; SetParent(table, nodeList[i].cur, nodeList[i].next); //int min = Math.Min(table[nodeList[i].cur], table[nodeList[i].next]); //int max = Math.Max(table[nodeList[i].cur], table[nodeList[i].next]); //table[nodeList[i].cur] = table[nodeList[i].next] = min; //for (int j = 0; j < table.Length; j++) //{ // if (table[j] == max) // { // table[j] = min; // } //} } } return answer; } } }