Problem:


Score : 400 points

Problem Statement

On a planet far, far away, M languages are spoken. They are conveniently numbered 1 through M.

For CODE FESTIVAL 20XX held on this planet, N participants gathered from all over the planet.

The i-th (1≦i≦N) participant can speak K_i languages numbered L_{i,1}, L_{i,2}, ..., L_{i,{}K_i}.

Two participants A and B can communicate with each other if and only if one of the following conditions is satisfied:

There exists a language that both A and B can speak.

There exists a participant X that both A and B can communicate with.

Determine whether all N participants can communicate with all other participants.

Constraints

2≦N≦10^5

1≦M≦10^5

1≦K_i≦M

(The sum of all K_i)≦10^5

1≦L_{i,j}≦M

L_{i,1}, L_{i,2}, ..., L_{i,{}K_i} are pairwise distinct.

Partial Score

200 points will be awarded for passing the test set satisfying the following: N≦1000, M≦1000 and (The sum of all K_i)≦1000.

Additional 200 points will be awarded for passing the test set without additional constraints.

Input

The input is given from Standard Input in the following format:

N M
K_1 L_{1,1} L_{1,2} ... L_{1,{}K_1}
K_2 L_{2,1} L_{2,2} ... L_{2,{}K_2}
:
K_N L_{N,1} L_{N,2} ... L_{N,{}K_N}

Output

If all N participants can communicate with all other participants, print YES. Otherwise, print NO.

Sample Input 1

4 6
3 1 2 3
2 4 2
2 4 6
1 6

Sample Output 1

YES

Any two participants can communicate with each other, as follows:

Participants 1 and 2: both can speak language 2.

Participants 2 and 3: both can speak language 4.

Participants 1 and 3: both can communicate with participant 2.

Participants 3 and 4: both can speak language 6.

Participants 2 and 4: both can communicate with participant 3.

Participants 1 and 4: both can communicate with participant 2.

Note that there can be languages spoken by no participant.

Sample Input 2

4 4
2 1 2
2 1 2
1 3
2 4 3

Sample Output 2

NO

For example, participants 1 and 3 cannot communicate with each other.



Sample input:
4 6
3 1 2 3
2 4 2
2 4 6
1 6


Sample output:
YES

Submission status: Wrong Answer

Solution code:
from sys import stdin, stdout
def readLine_int_list():return list(map(int, stdin.readline().split()))

def find(x):
    if par[x] == x:
        return x
    else:
        par[x] = find(par[x])
        return par[x]
        
def unite(x,y):
    x = find(x)
    y = find(y)
    
    if x==y: return
    if rank[x]<rank[y]:
        par[x] = y
    else:
        par[y] = x
        if rank[x] == rank[y]:
            rank[x]+=1
            
def same(x,y):
    return find(x)==find(y)
    
n,m = readLine_int_list()
v = n + m
par = [i for i in range(0, n)]
rank = [1] * n
def main():
    G = [readLine_int_list()[1:] for i in range(n)]
    
    for i in range(n):
        for ii in readLine_int_list()[1:]:
    
           unite(i, ii)
           
    r = "YES"
    for i in range(0, n):
        if find(i) != find(0):
            r = "NO"
    print(r)
    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from sys import stdin, stdout
def readLine_int_list():return list(map(int, stdin.readline().split()))

def find(x):
    if par[x] == x:
        return x
    else:
        par[x] = find(par[x])
        return par[x]
        
def unite(x,y):
    x = find(x)
    y = find(y)
    
    if x==y: return
    if rank[x]<rank[y]:
        par[x] = y
    else:
        par[y] = x
        if rank[x] == rank[y]:
            rank[x]+=1
            
def same(x,y):
    return find(x)==find(y)
    
n,m = readLine_int_list()
v = n + m
par = [i for i in range(0, n)]
rank = [1] * n
def main():
    G = [readLine_int_list()[1:] for i in range(n)]
    
    for i in range(n):
        for ii in readLine_int_list()[1:]:
    
           unite(i, ii)
           
    print("YES" if len(set(par)) == 1 else "NO")
    
if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
from sys import stdin, stdout
def readLine_int_list():return list(map(int, stdin.readline().split()))

def get_root(n):
    if n == v[n]:
        return n
    else:
        v[n] = get_root(v[n])
        return v[n]
 
def unite(a,b):
    a, b = get_root(a), get_root(b)
    if a!=b:
        v[b] = a
        
def same(a,b):
    return get_root(a) == get_root(b)
    

n,m = readLine_int_list()
v = [i for i in range(n)]
def main():
    G = [readLine_int_list()[1:] for i in range(n)]
    
    for i in range(n):
        for ii in G[i]:
            for j in range(i+1,n):
                if ii in G[j]:
                    unite(i,j)

    if len(set(v)) == 1:
        print("YES")
    else:
        print("NO")

if __name__ == '__main__':
    main()

Submission status: Wrong Answer

Solution code:
print('YES')

Submission status: Wrong Answer

Solution code:
[N, M] = map(int, raw_input().split(' '))
arr = [[False] * N for i in range(N)]
language = []
for i in range(N):
    language.append(set(raw_input().split(' ')[1:]))

modified = True
while modified:
    is_modified = False
    for i in range(N):
        for j in range(N-i):
            if i == i + j:
                continue
            elif arr[i][i+j] == True:
                continue
            else:
                # First check language
                if len(language[i].intersection(language[i+j])) > 0:
                    arr[i][i + j] = True
                    arr[i+j][i] = True
                    is_modified = True
                # Then check neighbour
                else:
                    for a in range(N):
                        if arr[i][a] == True and arr[i+j][a] == True:
                            arr[i][i + j] = True
                            arr[i+j][i] = True
                            is_modified = True
                            break
    modified = is_modified

for i in range(N):
    for j in range(N-i):
        if arr[i][i+j] != True:
            print "No"
            exit()
print "Yes"

Submission status: Wrong Answer

Solution code:
[N, M] = map(int, raw_input().split(' '))
arr = [[False] * N for i in range(N)]
language = []
for i in range(N):
    language.append(set(raw_input().split(' ')[1:]))

modified = True
while modified:
    is_modified = False
    for i in range(N):
        for j in range(N-i):
            print i, i + j
            if i == i + j:
                continue
            elif arr[i][i+j] == True:
                continue
            else:
                # First check language
                if len(language[i].intersection(language[i+j])) > 0:
                    arr[i][i + j] = True
                    arr[i+j][i] = True
                    is_modified = True
                # Then check neighbour
                else:
                    for a in range(N):
                        if arr[i][a] == True and arr[i+j][a] == True:
                            arr[i][i + j] = True
                            arr[i+j][i] = True
                            is_modified = True
                            break
    modified = is_modified

for i in range(N):
    for j in range(N-i):
        if arr[i][i+j] != True:
            print "No"
            exit()
print "Yes"

Submission status: Wrong Answer

Solution code:
[N, M] = map(int, raw_input().split(' '))
arr = [[False] * N for i in range(N)]
language = []
for i in range(N):
    language.append(set(raw_input().split(' ')[1:]))

modified = True
while modified:
    is_modified = False
    for i in range(N):
        for j in range(N-i):
            print i, i + j
            if i == i + j:
                continue
            elif arr[i][i+j] == True:
                continue
            else:
                # First check language
                if len(language[i].intersection(language[i+j])) > 0:
                    arr[i][i + j] = True
                    arr[i+j][i] = True
                    is_modified = True
                # Then check neighbour
                else:
                    for a in range(N):
                        if arr[i][a] == True and arr[i+j][a] == True:
                            arr[i][i + j] = True
                            arr[i+j][i] = True
                            is_modified = True
                            break
    modified = is_modified
print arr
for i in range(N):
    for j in range(N-i):
        if arr[i][i+j] != True:
            print "No"
            exit()
print "Yes"

Submission status: Wrong Answer

Solution code:
import sys
N, M = map(int, input().split())
can_talk = [i for i in range(N)]
lang = [[] for _ in range(M)]
for i in range(N):
	L = [int(i) for i in input().split()]
	L.reverse()
	L.pop()
	for l in L:
		if lang[l-1]:
			can_talk[lang[l-1][0]] = i
		else:
			lang[l-1].append(i)

	for i in range(N):
		s = i
		p = []
		while s != can_talk[s]:
			p.append(s)
			s = can_talk[s]
		for x in p:
			can_talk[x] = s
if can_talk.count(can_talk[0]) == N:
	print("YES")
else:
	print("NO")

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf = 10**10
mod = 10**9 + 7

class UnionFind:
    def __init__(self, size):
        self.table = [-1 for _ in range(size)]

    def find(self, x):
        if self.table[x] < 0:
            return x
        else:
            self.table[x] = self.find(self.table[x])
            return self.table[x]

    def union(self, x, y):
        s1 = self.find(x)
        s2 = self.find(y)
        if s1 != s2:
            if self.table[s1] <= self.table[s2]:
                self.table[s1] += self.table[s2]
                self.table[s2] = s1
            else:
                self.table[s2] += self.table[s1]
                self.table[s1] = s2
            return True
        return False

    def subsetall(self):
        a = []
        for i in range(len(self.table)):
            if self.table[i] < 0:
                a.append((i, -self.table[i]))
        return a

def f():
    n,m = list(map(int, input().split()))
    a = list(range(m+1))
    g = [False]*(m+1)
    uf = UnionFind(m+1)
    mi = None
    for _ in range(n):
        c = list(map(int, input().split()))
        if not mi:
            mi = c[1]
        g[c[1]] = True
        if c[0] > 1:
            for i in range(c[0]-1):
                g[c[2+i]] = True
                uf.union(c[1], c[2+i])

    t = uf.find(mi)

    for i in range(mi+1,m+1):
        if not g[i]:
            continue
        if uf.find(i) != t:
            return 'NO'
    return 'YES'



print(f())

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf = 10**10
mod = 10**9 + 7

class UF:
    rank = []
    par = []
    f = []
    def __init__(self, n):
        self.n = n
        for i in range(n):
            self.rank.append(0)
            self.par.append(i)
        self.f = [False] * n

    def add(self, x):
        self.f[x] = True

    def find(self, x):
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def unite(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if x == y:
            return
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
        else:
            self.par[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    def same(self, x, y):
        return self.find(x) == self.find(y)

def f():
    n,m = list(map(int, input().split()))
    a = list(range(m+1))
    b = [inf]*(m+1)
    uf = UF(m+1)
    mi = None
    for _ in range(n):
        c = list(map(int, input().split()))
        if not mi:
            mi = c[1]
        uf.add(c[1])
        if c[0] > 1:
            for i in range(c[0]-1):
                uf.add(c[2+i])
                uf.unite(c[1], c[2+i])

    for i in range(mi+1,m+1):
        if not uf.f[i]:
            continue
        if not uf.same(mi, i):
            return 'NO'
    return 'YES'



print(f())

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf = 10**10
mod = 10**9 + 7


def f():
    n,m = list(map(int, input().split()))
    a = list(range(m+1))
    b = [inf]*(m+1)
    for _ in range(n):
        c = list(map(int, input().split()))
        d = c[1:]
        mi = min(d)
        for e in d:
            if b[a[e]] < mi:
                mi = b[a[e]]
        for e in d:
            b[a[e]] = mi
            a[e] = mi
    s = set(b[_] for _ in a)
    if len(s) == 2:
        return 'YES'
    return 'NO'



print(f())

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf = 10**10
mod = 10**9 + 7


def f():
    n,m = list(map(int, input().split()))
    a = list(range(m+1))
    b = [inf]*(m+1)
    for _ in range(n):
        c = list(map(int, input().split()))
        d = c[1:]
        mi = min(d)
        for e in d:
            if b[a[e]] < mi:
                mi = b[a[e]]
        for e in d:
            b[a[e]] = mi
            a[e] = mi
    s = set(b)
    if len(s) == 2:
        return 'YES'
    return 'NO'



print(f())

Submission status: Wrong Answer

Solution code:
import math,string,itertools,fractions,heapq,collections,re,array,bisect,sys,random,time

sys.setrecursionlimit(10**7)
inf = 10**10
mod = 10**9 + 7


def f():
    n,m = list(map(int, input().split()))
    b = [inf]*(m+1)
    for _ in range(n):
        c = list(map(int, input().split()))
        d = c[1:]
        mi = min(d)
        for e in d:
            if b[e] < mi:
                mi = b[e]
        for e in d:
            b[e] = mi
    s = set(b)
    if len(s) == 2:
        return 'YES'
    return 'NO'



print(f())

Submission status: Wrong Answer

Solution code:
N, M = list(map(int, input().split()))

data_list = []
for i in range(N):
    tmp_list = list(map(int, input().split()))[1:]
    data_list.append(set(tmp_list))

class UnionFind:
    def __init__(self, count):
        root = [0] * count
        for i in range(count):
            root[i] = i
        self.root = root
    def unite(self, a, b):
        root = self.root
        root[a] = b
    def find(self, a):
        r = self.root[a]
        if (a == r):
            return a
        else:
            r = self.find(r)
            self.root[a] = r
            return r

uf = UnionFind(N)

for i in range(N):
    for j in range(i + 1, N):
        if(len(data_list[i] & data_list[j]) > 0):
            uf.unite(i, j)


b = True
for i in range(N):
    for j in range(i + 1, N):
        if(not uf.find(i) == uf.find(j)):
            b = False
            break
    if(not b):
        break
    
print('YES' if b else 'NO')

Submission status: Wrong Answer

Solution code:
N, M = list(map(int, input().split()))

data_list = []
for i in range(N):
    tmp_list = list(map(int, input().split()))[1:]
    data_list.append(set(tmp_list))

class UnionFind:
    def __init__(self, count):
        root = [0]*count
        for i in range(count):
            root[i] = i
        self.root = root
    def unite(self, a, b):
        root = self.root
        root[a] = b
    def find(self, a):
        r = self.root[a]
        return a if a==r else self.find(r)

uf = UnionFind(N)

for i in range(N):
    for j in range(i+1,N):
        if(len(data_list[i]&data_list[j])>0):
            uf.unite(i, j)


b = True
for i in range(N):
    for j in range(i+1,N):
        if(not uf.find(i)==uf.find(j)):
            b=False
            break
    if(not b):
        break
    
print('YES' if b else 'NO')

Submission status: Wrong Answer

Solution code:
n,m=map(int,raw_input().split())
l=[]
for i in range(n):
    tmp=map(int,raw_input().split())
    l.append(set(tmp[1:]))
for i in range(n-1):
    for j in range(i+1,n):
        if not l[i]&l[j]:
            for k in range(n):
                if k!=i and k!=j:
                    if l[i]&l[k] and l[j]&l[k]:
                        break
            print 'NO'
            exit()
print 'YES'

Submission status: Wrong Answer

Solution code:
n,m=map(int,raw_input().split())
#l=map(int,raw_input().split())
l=[]
for i in range(n):
    tmp=map(int,raw_input().split())
    l.append(set(tmp[1:]))
for i in range(n-1):
    for j in range(i+1,n):
        if not l[i]&l[j]:
            for k in range(n):
                if k!=i and k!=j:
                    if l[i]&l[k] and l[j]&l[k]:
                        pass
                    else:
                        print 'NO'
                        exit()
print 'YES'

Submission status: Wrong Answer

Solution code:
import sys
import numpy as np

#f = open("input.txt")
f = input()

NM = f.split(' ')
N = int(NM[0])
M = int(NM[1])

K = []
L = []
for i in range(N):
    line = input().rstrip('\n').split(' ')
    K.append( int(line[0]))
    L.append(set(line[1:]))
    # print(line)

# print(K)
# print(L)

while True:
    tmp = L
    for x in range(len(L)):
        for y in range(x+1, len(L)):
            if x == y:
                continue
            if list(L[x] & L[y]) != []:
                L[x] = L[y] = L[x] | L[y]
    # print(L)

    if tmp == L:
        break

flag = True
comp = L[0]
for l in L:
    if list(comp ^ l) != []:
        flag = False
        break

if flag:
    print("YES")
else :
    print("NO")

# for n in out:
#     print(n)

# print(' '.join(map(str, out)))

Submission status: Wrong Answer

Solution code:
import sys

def have_in_common(person1, person2):
	for lang in person1:
		for lang2 in person2:
			if lang == lang2:
				return True
	return False

N, M = map(int, input().split())

persons = []
for i in range(N):
	person = sys.stdin.readline().split()
	persons.append(person[1:])

for i in range(len(persons)):
	for j in range(i+1,len(persons)):
		if have_in_common(persons[i],persons[j]) == False:
			for person in persons:
				if (person != persons[i]) and (person != persons[j]):
					if have_in_common(persons[i],person):
						if have_in_common(persons[j],person):
							break
			else:
				print("NO")
				sys.exit()
print("YES")

Submission status: Wrong Answer

Solution code:
import sys

next(sys.stdin)

_, *langs = map(int, next(sys.stdin).strip().split())
common_langs = set(langs)

unreachable = list()
for line in sys.stdin:
    _, *langs = map(int, line.strip().split())
    unreachable.append(set(langs))

change = True
while change:
    change = False
    for langs in unreachable:
        if len(common_langs & langs) > 0:
            s = len(common_langs)
            common_langs.update(langs)
            change |= not s == len(common_langs)
            unreachable.pop(0)

if len(unreachable) == 0:
    print('YES')
else:
    print('NO')

Submission status: Wrong Answer

Solution code:
import array

def solve():
    n, m = map(int, input().split())
    humanSpeakLanguages = []
    for _ in range(n):
        language = array.array("I", [int(i) for i in input().split()])
        humanSpeakLanguages.append(language[1:])
    humanSpeakLanguages.sort(key=lambda x: x[0])
    languageSet = set(humanSpeakLanguages[0])
    humanSpeakLanguages.pop(0)
    for elem in humanSpeakLanguages:
        elemset = set(elem)
        tresult = languageSet & elemset
        if len(tresult) == 0:
            print("NO")
            return
        languageSet |= elemset
    print("YES")

if __name__=="__main__":
    solve()

Submission status: Wrong Answer

Solution code:
import array

def solve():
    n, m = map(int, input().split())
    humanSpeakLanguages = []
    for _ in range(n):
        language = array.array("I", [int(i) for i in input().split()])
        humanSpeakLanguages.append(language[1:])
    humanSpeakLanguages.sort()
    languageSet = set(humanSpeakLanguages[0])
    humanSpeakLanguages.pop(0)
    for elem in humanSpeakLanguages:
        elemset = set(elem)
        tresult = languageSet & elemset
        if len(tresult) == 0:
            print("NO")
            return
        languageSet |= elemset
    print("YES")

if __name__=="__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
N,M=map(int,input().split())
from collections import defaultdict
branch=defaultdict(set)
lang=defaultdict(set)
inp=[]
for i in range(N):
    X=list(map(int,input().split()))
    for k in range(X[0]):
        lang[X[k+1]]|={i}
    inp.append(X[1:])
for i in range(N):
    for l in inp[i]:
        branch[i]|=lang[l]
checked={0}
check={0}
while len(check)>0:
    now=check.pop()
    check|=branch[now]-checked
    checked|=branch[now]
    if len(checked)==N:
        break
if len(checked)==N:
    print('YES')
else:
    print('NO')

Submission status: Time Limit Exceeded

Solution code:
import sys
def input():
    return sys.stdin.readline()[:-1]
N, M = map(int,input().split())
H = []
L = [[] for k in range(M+1)]

for k in range(N):
    P = list(map(int,input().split()))[1:]
    H.append(P)
    for e in P:
        L[e].append(k+1)

G = [0 for k in range(N+1)]
G[1] = 1
Q = [H[0]]
while len(Q) > 0:
    ima = Q.pop()
    for tsugi in ima:
        for e in L[tsugi]:
            if G[e] == 0:
                G[e] = 1
                Q.append(H[e-1])

for k in range(1,N+1):
    if G[k] == 0:
        print("NO")
        exit(0)
print("YES")

Submission status: Time Limit Exceeded

Solution code:
N, M = map(int,input().split())
H = []
L = [[] for k in range(M+1)]

for k in range(N):
    P = list(map(int,input().split()))[1:]
    H.append(P)
    for e in P:
        L[e].append(k+1)

G = [0 for k in range(N+1)]
G[1] = 1
Q = [H[0]]
while len(Q) > 0:
    ima = Q.pop()
    for tsugi in ima:
        for e in L[tsugi]:
            if G[e] == 0:
                G[e] = 1
                Q.append(H[e-1])

for k in range(1,N+1):
    if G[k] == 0:
        print("NO")
        exit(0)
print("YES")

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**6)
n,m=map(int,input().split())
a=[[]for i in range(n+m)]
for i in range(n):
    s=list(map(int,input().split()))
    for j in s[1:]:
        a[i].append(j)
        a[n+j-1].append(i)
t=[False]*n
def g(x):
    if not t[x]:
        t[x]=True
        for i in a[x]:
            for j in a[i+n-1]:
                g(j)
g(0)
if all(t):
    print("YES")
else:
    print("NO")

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(10**9)
n,m=map(int,input().split())
a=[[]for i in range(n+m)]
for i in range(n):
    s=list(map(int,input().split()))
    for j in s[1:]:
        a[i].append(j)
        a[n+j-1].append(i)
t=[False]*n
def g(x):
    if not t[x]:
        t[x]=True
        for i in a[x]:
            for j in a[i+n-1]:
                g(j)
g(0)
if all(t):
    print("YES")
else:
    print("NO")

Submission status: Time Limit Exceeded

Solution code:
import sys
sys.setrecursionlimit(100000)

n, m = map(int, input().split())

people = []
lang = [[] for _ in range(m)]

for i in range(n):
  kl = list(map(int, input().split()))
  k = kl[0]
  people.append(kl[1:])
  for l in kl[1:]:
    lang[l-1].append(i)

visited = [False for _ in range(n)]

def dfs(i):
  if visited[i]:
    return
  else:
    visited[i] = True
    for l in people[i]:
      for nexp in lang[l-1]:
        dfs(nexp)

dfs(0)

if all(visited):
  print('YES')
else:
  print('NO')

Submission status: Time Limit Exceeded

Solution code:
n, m = map(int,input().split())
data = [list(map(int,input().split())) for _ in range(n)]
class UnionFind:
    def __init__(self, n):
        # 親要素のノード番号を格納　par[x] == x の時そのノードは根
        self.par = [i for i in range(n+1)]
        # 木の高さを格納する（初期状態では0)
        self.rank = [0] * (n+1)
        # 各々の集合の要素数（根が代表して値を持っておく）
        self.count = [1] * (n+1)

    # 検索
    def find(self, x):
        # 根ならその番号を返す
        if self.par[x] == x:
            return x
        # 根でないなら親の要素で再検索
        else:
            # 検索する過程で親を更新
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    # 併合
    def union(self, x, y):
        x = self.find(x)
        y = self.find(y)
        if self.rank[x] < self.rank[y]:
            self.par[x] = y
            self.count[y] += self.count[x]
            self.count[x] = 0
        else:
            self.par[y] = x
            self.count[x] += self.count[y]
            self.count[y] = 0
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1

    # 同じ集合に属しているか判定
    def same_check(self, x, y):
        return self.find(x) == self.find(y)

    # 属している集合の要素数
    def size(self,x):
        q = UnionFind.find(self,x)
        return self.count[q]

u = UnionFind(n)
for i in range(1,m+1):
    p = 0
    for j in range(n):
        if p == 0 and i in data[j][1:]:
            q = j
            p = 1
        elif i in data[j][1:] and not u.same_check(j,q):
            u.union(j,q)

if u.size(0) == n:
    print('YES')
else:
    print('NO')

Submission status: Time Limit Exceeded

Solution code:
import sys


class Unionfindtree:
    def __init__(self, number):
        self.par = [i for i in range(number)]
        self.rank = [0] * (number)

    def find(self, x):  # 親を探す
        if self.par[x] == x:
            return x
        else:
            self.par[x] = self.find(self.par[x])
            return self.par[x]

    def union(self, x, y):  # x,yを繋げる
        px = self.find(x)
        py = self.find(y)
        if px == py:
            return
        if self.rank[px] < self.rank[py]:
            self.par[px] = py
        else:
            self.par[py] = px
        if self.rank[px] == self.rank[py]:
            self.rank[px] += 1

    def connect(self, x, y):  # 親が同じかみる
        return self.find(x) == self.find(y)


N,M=map(int,input().split())
K=[set() for i in range(M)]
tree=Unionfindtree(N)
for i in range(N):
    L=[int(i)-1 for i in input().split()]
    for m in L[1:]:
        K[m].add(i)
for i in range(M):
    Ki=list(K[i])
    for h in range(len(Ki)):
        for m in range(h+1,len(Ki)):
            tree.union(Ki[h],Ki[m])
for i in range(N):
    if not tree.connect(0,i):
        print('NO')
        sys.exit()
print('YES')

Submission status: Time Limit Exceeded

Solution code:
# 入力
import sys
stdin = sys.stdin

def li(): return [int(x) for x in stdin.readline().split()]
def li_(): return [int(x)-1 for x in stdin.readline().split()]
def lf(): return [float(x) for x in stdin.readline().split()]
def ls(): return stdin.readline().split()
def ns(): return stdin.readline().rstrip()
def lc(): return list(ns())
def ni(): return int(ns())
def nf(): return float(ns())

def dfs(graph:list, node:int, start:int) -> list:
    # 未探索のノードは距離INF
    INF = float("inf")
    dist = [INF]*node
    
    # 始点ノードの距離を0とし、dfsのためのstackを作成
    dist[start] = 0
    stack = [(0,start)]
    
    while stack:
        cost, cur_node = stack.pop()

        # 未探索のノードをstackに入れる
        for nex_cost, nex_node in graph[cur_node]:
            if dist[nex_node] != INF:
                continue
            else:
                dist[nex_node] = dist[cur_node] + nex_cost
                stack.append((dist[nex_node],nex_node))
                
    return dist

from collections import defaultdict

dic = defaultdict(list)

n,m = li()

# 各言語を話せる人を登録
for i in range(n):
    l_list = li()
    for l in l_list[1:]:
        dic[l].append(i)
        
# 隣接リストを作成
adj_list = [[] for _ in range(n)]
for key in dic.keys():
    values = dic[key]
    while len(values) > 1:
        v = values.pop()
        for j in values:
            adj_list[v].append((1,j))
            adj_list[j].append((1,v))
            
# dfsを実行して、距離がINFのものがあればNO
INF = float("inf")
dist = dfs(adj_list, n, 0)

if INF in dist:
    print("NO")
else:
    print("YES")

Submission status: Time Limit Exceeded

Solution code:
from sys import stdin, stdout
def readLine_int_list():return list(map(int, stdin.readline().split()))

def find(x):
    if par[x] == x:
        return x
    else:
        par[x] = find(par[x])
        return par[x]
        
def unite(x,y):
    x = find(x)
    y = find(y)
    
    if x==y: return
    if rank[x]<rank[y]:
        par[x] = y
    else:
        par[y] = x
        if rank[x] == rank[y]:
            rank[x]+=1
            
def same(x,y):
    return find(x)==find(y)
    
n,m = readLine_int_list()
v = n + m
par = [i for i in range(0, n)]
rank = [1] * n
def main():
    G = [readLine_int_list()[1:] for i in range(n)]
    
    for i in range(n):
        for ii in G[i]:
            for j in range(i+1,n):
                if ii in G[j]:
                    unite(i,j)

    # print(par)
    
    r = "YES"
    for i in range(0, n):
        if find(i) != find(0):
            r = "NO"
    print(r)
    
    
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
N, M = list(map(int, input().split()))
 
data_list = []
for i in range(N):
    tmp_list = list(map(int, input().split()))[1:]
    data_list.append(set(tmp_list))
 
class UnionFind:
    def __init__(self, count):
        root = [0] * count
        for i in range(count):
            root[i] = i
        self.root = root
    def unite(self, a, b):
        root = self.root
        root[self.find(a)] = self.find(b)
    def find(self, a):
        r = self.root[a]
        if (a == r):
            return a
        else:
            r = self.find(r)
            self.root[a] = r
            return r
 
uf = UnionFind(N)
 
for i in range(N):
    for j in range(i + 1, N):
        if(len(data_list[i] & data_list[j]) > 0):
            uf.unite(i, j)
 
 
b = True
for i in range(N):
    for j in range(i + 1, N):
        if(not uf.find(i) == uf.find(j)):
            b = False
            break
    if(not b):
        break
    
print('YES' if b else 'NO')

Submission status: Time Limit Exceeded

Solution code:
import array

def solve():
    n, m = map(int, input().split())
    humanSpeakLanguages = []
    for _ in range(n):
        language = array.array("I", [int(i) for i in input().split()])
        humanSpeakLanguages.append(language[1:])
    stack = set(humanSpeakLanguages[0])
    humanSpeakLanguages.pop(0)
    while len(humanSpeakLanguages) > 0:
        stacklength = len(stack)
        removeIdxs = array.array("I")
        for (i, language) in enumerate(humanSpeakLanguages):
            lset = set(language)
            if len(lset & stack):
                stack |= lset
                removeIdxs.append(i)

        for elem in removeIdxs[::-1]:
            humanSpeakLanguages.pop(elem)

        if stacklength == len(stack):
            break

    if len(humanSpeakLanguages) > 0:
        print("NO")
    else:
        print("YES")

if __name__=="__main__":
    solve()

Submission status: Time Limit Exceeded

Solution code:
import array

def solve():
    n, m = map(int, input().split())
    humanSpeakLanguages = []
    for _ in range(n):
        language = array.array("I", [int(i) for i in input().split()])
        humanSpeakLanguages.append(language[1:])
    stack = set(humanSpeakLanguages[0])
    humanSpeakLanguages.pop(0)
    while len(humanSpeakLanguages) > 0:
        stacklength = len(stack)
        removeIdxs = array.array("I")
        for (i, language) in enumerate(humanSpeakLanguages):
            lset = set(language)
            if len(lset & stack):
                stack |= set(language)
                removeIdxs.append(i)

        for elem in removeIdxs[::-1]:
            humanSpeakLanguages.pop(elem)

        if stacklength == len(stack):
            break

    if len(humanSpeakLanguages) > 0:
        print("NO")
    else:
        print("YES")

if __name__=="__main__":
    solve()