File tree Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Expand file tree Collapse file tree 1 file changed +57
-0
lines changed Original file line number Diff line number Diff line change 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 )
You can’t perform that action at this time.
0 commit comments