Skip to content

Commit 7ea9f84

Browse files
committed
added journey-to-the-moon
1 parent e3347f5 commit 7ea9f84

File tree

1 file changed

+57
-0
lines changed

1 file changed

+57
-0
lines changed
Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
import math
2+
import os
3+
import random
4+
import re
5+
import sys
6+
from collections import Counter
7+
8+
def dfs(g, u, discovered, c):
9+
for v in g[u]:
10+
if v not in discovered:
11+
discovered[v] = c
12+
dfs(g, v, discovered, c)
13+
14+
def journeyToMoon(n, astronaut):
15+
g = {}
16+
for i in range(n):
17+
g[i] = set()
18+
19+
for a, b in astronaut:
20+
g[a].add(b)
21+
g[b].add(a)
22+
23+
forest = {}
24+
component = 0
25+
for v in range(n):
26+
if v not in forest:
27+
forest[v] = component
28+
dfs(g, v, forest, component)
29+
component += 1
30+
31+
vs = Counter(forest.values()).values()
32+
33+
c_sum = 0
34+
result = 0
35+
for s in vs:
36+
result += c_sum * s
37+
c_sum += s
38+
39+
return result
40+
41+
if __name__ == '__main__':
42+
f = open('/home/elijah/Downloads/input13.txt')
43+
44+
np = f.readline().split()
45+
46+
n = int(np[0])
47+
48+
p = int(np[1])
49+
50+
astronaut = []
51+
52+
for _ in range(p):
53+
astronaut.append(list(map(int, f.readline().rstrip().split())))
54+
55+
result = journeyToMoon(n, astronaut)
56+
57+
print(result)

0 commit comments

Comments
 (0)