[HackerRank][Python3] Roads and Libraries
2018. 7. 22. 17:43 |
프로그래밍/HackerRank
Problem :
https://www.hackerrank.com/challenges/torque-and-development/problem
My Solution :
#!/usr/bin/env python3 def dfs(nodes, node, visited): if visited[node]: return 0 visited[node] = 1 count = 1 for neighbor in nodes[node]: count += dfs(nodes, neighbor, visited) return count def roadsAndLibraries(n, c_lib, c_road, cities): nodes = {i+1: [] for i in range(n)} visited = [0]*(n+1) for u, v in cities: nodes[u].append(v) nodes[v].append(u) cost = 0 for node in nodes: count = dfs(nodes, node, visited) if count: cost += c_lib + (count-1)*min(c_lib, c_road) return cost q = int(input()) for _ in range(q): n, m, c_lib, c_road = map(int, input().split()) cities = [] for _ in range(m): cities.append(list(map(int, input().rstrip().split()))) result = roadsAndLibraries(n, c_lib, c_road, cities) print(result)
'프로그래밍 > HackerRank' 카테고리의 다른 글
[HackerRank][Python3] Swap Nodes [Algo] (0) | 2018.07.27 |
---|---|
[HackerRank][Python3] Special Palindrome Again (0) | 2018.07.23 |
[HackerRank][Python3] Fraudulent Activity Notifications (0) | 2018.07.23 |
[HackerRank][Python3] Merge Sort: Counting Inversions (0) | 2018.07.22 |
[HackerRank][Python3] BFS: Shortest Reach in a Graph (0) | 2018.07.22 |
[HackerRank][Python3] Find the nearest clone (0) | 2018.07.22 |
[HackerRank][Python3] DFS: Connected Cell in a Grid (0) | 2018.07.21 |
[HackerRank][Python3] Friend Circle Queries (0) | 2018.07.21 |
최근에 달린 댓글 최근에 달린 댓글