Skip to content

Instantly share code, notes, and snippets.

@binhngoc17
Created December 14, 2014 15:43
Show Gist options
  • Save binhngoc17/959b1c8853a263c54ad5 to your computer and use it in GitHub Desktop.
Save binhngoc17/959b1c8853a263c54ad5 to your computer and use it in GitHub Desktop.
Use combinations & Union Find Algo
from itertools import combinations
N,l = map(int,raw_input().split())
sets = []
idx = dict((i, i) for i in range(N))
for i in xrange(l):
a,b = map(int,raw_input().split())
val = idx[a]
for i in idx:
if idx[i] == val:
idx[i] = idx[b]
sets = {}
for val in set(idx.values()):
sets[val] = set([])
for i in idx.keys():
if idx[i] == val:
sets[val].add(i)
total = 0
for g in combinations(sets.values(), 2):
total += len(g[0]) * len(g[1])
print total
@binhngoc17
Copy link
Author

N,l = map(int,raw_input().split())

sets = []

idx = dict((i, i) for i in range(N))
print idx

for i in xrange(l):
a,b = map(int,raw_input().split())
set_a = set([a])
set_b = set([b])

for s in sets:
    if a in s:
        mark = True
        s.add(b)
    if b in s:
        mark = True
        s.add(a)
if not mark:
    s = set([a, b])
    sets.append(s)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment