Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit d7ab9fb

Browse files
committed
[hackerrank] merging_communities
1 parent 2c41382 commit d7ab9fb

2 files changed

Lines changed: 92 additions & 0 deletions

File tree

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
# Merging Communities
2+
3+
People connect with each other in a social network. A connection between
4+
Person I and Person J is represented as M I J. When two persons belonging to
5+
different communities connect, the net effect is the merger of both
6+
communities which I and J belongs to.
7+
8+
At the beginning, there are N people representing N communities. Suppose
9+
person 1 and 2 connected and later 2 and 3 connected, then 1, 2, and 3 will
10+
belong to the same community.
11+
12+
There are two type of queries:
13+
14+
1. M I J => communities containing person I and J merged (if they belong to
15+
different communities).
16+
17+
2. Q I => print the size of the community to which person I belongs.
18+
19+
## Input format
20+
21+
The first line of input will contain integers N and Q, i.e. the number of
22+
people and the number of queries. The next Q lines will contain the queries.
23+
24+
## Output format
25+
26+
The output of the queries.
27+
28+
## Sample input
29+
30+
3 6
31+
Q 1
32+
M 1 2
33+
Q 2
34+
M 2 3
35+
Q 3
36+
Q 2
37+
38+
## Sample output
39+
40+
1
41+
2
42+
3
43+
3
Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
#!/bin/python
2+
3+
# Use quick-union approach described here:
4+
# https://www.cs.princeton.edu/~rs/AlgsDS07/01UnionFind.pdf
5+
6+
from collections import deque
7+
8+
N, Q = map(int,input().strip().split(' '))
9+
10+
# 1st index is dummy placeholder since input is 1-indexed
11+
s = [i for i in range(N+1)]
12+
cnt = [0]+[1 for i in range(N)]
13+
14+
# follow parent indices to root, store intermediates in list
15+
def findparent(c, d):
16+
while c != s[c]:
17+
d.append(c)
18+
c = s[c]
19+
return c
20+
21+
# set all intermediate indices to parent
22+
def percolate(p, d):
23+
for i in d:
24+
s[i] = p
25+
26+
for i in range(Q):
27+
inpt = input().strip().split(' ')
28+
qry = inpt[0]
29+
a = sorted(map(lambda x: int(x),inpt[1:]))
30+
i0 = a[0]
31+
32+
if qry == 'Q':
33+
if i0 != s[i0]:
34+
d = deque()
35+
i0 = findparent(i0, d)
36+
percolate(i0, d)
37+
print(cnt[i0])
38+
continue
39+
40+
# qry == 'M'
41+
i1 = a[1]
42+
if s[i0] != s[i1]:
43+
d = deque()
44+
i0 = findparent(i0, d)
45+
i1 = findparent(i1, d)
46+
if s[i0] != s[i1]:
47+
cnt[i0] += cnt[i1]
48+
d.append(i1)
49+
percolate(i0, d)

0 commit comments

Comments
 (0)