[HackerRank][Python3] Journey to the Moon
2018. 5. 25. 02:52 |
프로그래밍/HackerRank
Problem :
https://www.hackerrank.com/challenges/journey-to-the-moon/problem
My Solution :
#!/usr/bin/env python3
def journeyToMoon(n, astronaut):
country = {x: 0 for x in range(n)}
c_code = 1
for a1, a2 in astronaut:
c1, c2 = country[a1], country[a2]
if c1 == c2 == 0:
country[a1], country[a2] = c_code, c_code
c_code += 1
elif c1 * c2 == 0:
c = max(c1, c2)
country[a1], country[a2] = c, c
elif c1 != c2:
for a, c in country.items():
if c == c2:
country[a] = c1
country_count = {}
for c in country.values():
country_count.setdefault(c, 0)
country_count[c] += 1
sum, res = 0, 0
for c in country_count.values():
res += sum * c
sum += c
singles = country_count.get(0, 0)
if singles > 1:
res += singles*(singles-1)//2
return res
n, p = map(int, input().strip().split())
astronaut = []
for _ in range(p):
astronaut.append(list(map(int, input().strip().split())))
result = journeyToMoon(n, astronaut)
print(result)
My Solution2:
#!/usr/bin/env python3
def find_set_index(a):
for i in range(len(a_set_list)):
if a in a_set_list[i]:
return i
def journeyToMoon(n, astronaut):
for a1, a2 in astronaut:
i1, i2 = find_set_index(a1), find_set_index(a2)
if i1 != i2:
a_set_list[i1] = a_set_list[i1].union(a_set_list[i2])
del a_set_list[i2]
sum, res = 0, 0
for s in a_set_list:
res += sum * len(s)
sum += len(s)
return res
n, p = map(int, input().strip().split())
astronaut = []
for _ in range(p):
astronaut.append(list(map(int, input().strip().split())))
a_set_list = [{x} for x in range(n)]
result = journeyToMoon(n, astronaut)
print(result)
'프로그래밍 > HackerRank' 카테고리의 다른 글
| [HackerRank][Python3] Construct the Array (0) | 2018.05.30 |
|---|---|
| [HackerRank][Python3] Minimum Absolute Difference in an Array (0) | 2018.05.29 |
| [HackerRank][Python3] Big Sorting (0) | 2018.05.29 |
| [HackerRank][Python3] CamelCase (0) | 2018.05.27 |
| [HackerRank][Python3] Hackerland Radio Transmitters (0) | 2018.05.23 |
| [HackerRank][Python3] Sherlock and Cost (0) | 2018.05.21 |
| [HackerRank][Python3] Maximum Subarray Sum (0) | 2018.05.18 |
| [HackerRank][Python3] Equal (0) | 2018.05.16 |
최근에 달린 댓글 최근에 달린 댓글