def solution(n, costs): answer = 0 V = set() for v1, v2, cost in costs: V.add(v1) V.add(v2) # collectiong total index and number of islands without duplication # used as unvisited set sortedCosts = sorted(costs, key = lambda x: x[2]) # make a sorted list, key : node connection, value : cost # it keeps the sequence of each elem in inner list, # but each inner list is sorted by lower cost # means this sort meet the minial cost condition # x:x[2] means, key value to sort by is x[2] item in inner list visited = set() visited.add(V.pop()) # put the first node index and thats it while V: for i in range(len(sortedCosts)): v1, v2, cost = sortedCosts[i] # how to spead and assign multiple items in one line if v1 in visited and v2 in visited: # means same connection with lower cost has already been confirmed # if the connection with lower cost has already confirmed sortedCosts.pop(i) break elif v1 in visited or v2 in visited: # add a new island, unvisited island into the graph # remove the one unvisited island from unvisited set, V if v1 in V: V.remove(v1) if v2 in V: V.remove(v2) visited.add(v1) visited.add(v2) # visited is a set, we dont know which one was unvisited # so we simply add two and only unvisited node will be added safely answer += cost # this tuple is counted as confirmed cost, add it sortedCosts.pop(i) # this tuple has processed, remove it # since this is whiled until there will be no node unvisited (V) # and start again from new index and length of sortedCosts break # I think reduced index of enumerate object(popping sortedCosts) might cause indexing error later # that is why each loop action does break and start again # until all islands are connected return answer costs = [[0,1,1],[0,2,2],[1,2,5],[1,3,1],[2,3,8]] n = 4solution(4, costs)
<HTML> <body> </body> <script> function Calculator() { let methods = { "-" : (a, b) => a - b, "+" : (a, b) => a + b }; //methods is an object which keeps key for operators //and value to return the actual operation values //each returns the result of operation that key(operator) does this.calculate = function (str){ //calculate is one element in the function Calculator //it takes the string and returns the value //in the function element list is delimeted by , not ; let split = str.split(" "), a = +split[0], op = split[1], b = split [2] if(!methods[op] || isNaN(a) || isNaN(b)) { return NaN; // error handling } return methods[op](a,b); } this.addMethod = function(name, func){ methods[name] = func; //this is how to add new key and ele to object } } let powerCalc = new Calculator; powerCalc.addMethod("*&
댓글
댓글 쓰기