Problem:


Score : 300 points

Problem Statement

There are N people numbered 1 to N. Each of them is either an honest person whose testimonies are always correct or an unkind person whose testimonies may be correct or not.

Person i gives A_i testimonies. The j-th testimony by Person i is represented by two integers x_{ij} and y_{ij}. If y_{ij} = 1, the testimony says Person x_{ij} is honest; if y_{ij} = 0, it says Person x_{ij} is unkind.

How many honest persons can be among those N people at most?

Constraints

All values in input are integers.

1 \leq N \leq 15

0 \leq A_i \leq N - 1

1 \leq x_{ij} \leq N

x_{ij} \neq i

x_{ij_1} \neq x_{ij_2} (j_1 \neq j_2)

y_{ij} = 0, 1

Input

Input is given from Standard Input in the following format:

N
A_1
x_{11} y_{11}
x_{12} y_{12}
:
x_{1A_1} y_{1A_1}
A_2
x_{21} y_{21}
x_{22} y_{22}
:
x_{2A_2} y_{2A_2}
:
A_N
x_{N1} y_{N1}
x_{N2} y_{N2}
:
x_{NA_N} y_{NA_N}

Output

Print the maximum possible number of honest persons among the N people.

Sample Input 1

3
1
2 1
1
1 1
1
2 0

Sample Output 1

2

If Person 1 and Person 2 are honest and Person 3 is unkind, we have two honest persons without inconsistencies, which is the maximum possible number of honest persons.

Sample Input 2

3
2
2 1
3 0
2
3 1
1 0
2
1 1
2 0

Sample Output 2

0

Assuming that one or more of them are honest immediately leads to a contradiction.

Sample Input 3

2
1
2 0
1
1 0

Sample Output 3

1



Sample input:
3
1
2 1
1
1 1
1
2 0


Sample output:
2

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
claim = []
MAX = 0

for i in range(N):
    A = int(input())
    claim.append([input().split() for i in range(A)])

for i in range(2 ** N):
    people = [0 for i in range(N)]
    FLAG = True
    for j in range(N):  
        if ((i >> j) & 1):  
            people[j] = 1

    c = [claim[i] for i in range(N) if people[i] == 1]
    
    for k in range(len(c)):
        for l in range(len(c[k])):
            if people[int(c[k][l][0]) - 1] != int(c[k][l][1]):
                FLAG = False
    
    if FLAG:
        MAX = max(MAX, sum(people))

print(MAX)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
A,B = [],[]
for i in range(N):
    n=int(input())
    A.append(n)
    for k in range(n):
        x,y = map(int,input().split())
        B.append([i,x,y])
ans = 0
for i in range(2**N):
    cnt = 0
    ok = True
    for j in range(N):
        #正直者を1にする
        if (i>>j) & 1:
            cnt += 1
            for k in range(len(B)):
                if B[k][0] == j:
                    if ((i >> (B[k][1]-1)) & 1) and B[k][2] == 1:
                        continue
                    elif ((i >> (B[k][1]-1)) & 1 == 0) and B[k][2] == 0:
                        continue
                    else:
                        ok = False
                        break
    if ok:
        ans = max(ans,cnt)
print(ans)

Submission status: Time Limit Exceeded

Solution code:

import numpy as np

# 入力
N = int(input())

A = []
Statement = np.zeros((N,N)) + 2

MaxNum = 0

for i in range(0,N):
    A.append(int(input()))
    for j in range(0,A[i]):
        X, Y = map(int,input().split())
        Statement[i,X-1]= Y

for i in range(0,2**N):
    ll = [int(x) for x in list(str(format(i,'b').zfill(N)))]
    l = np.array(ll)

    num = 0

    for check in range(0,N):
        if l[check] ==0 or sum(Statement[check,:] == l) == A[check]:
            num += 1
    
    if num == N:
        MaxNum = max(MaxNum,sum(l))

print(MaxNum)

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n=int(input())
a=[]
x=np.full((n, n), -1)
p=[]
pp=[[0]*n for i in range(2**n)]
for i in range(n):
    a.append(int(input()))
    for j in range(a[i]):
      X,Y=(map(int,input().split()))
      x[i][X-1]=Y

def rev(x):
    if x ==1:
        return 0
    else:
        return 1
        
def dec2bin(target):
    amari=[]
    while target !=0:
        amari.append(target % 2)
        target = target //2
    if len(amari)!=n:
        while len(amari)!=n:
            amari.append(0)
    amari.reverse()
    return amari

for i in range(2**n):
    p.append(dec2bin(i))
b=[]
for i in range(2**n):
  flag=True
  for j in range(n):
      if p[i][j]==1:
        for k in range(n):
          if( x[j][k]==1 and p[i][k]==0)or (x[j][k]==0 and p[i][k]==1):
            flag=False
            break
        if flag==False:
          break
  if flag:
    b.append(p[i].count(1))
    

if len(b)==0:
  print(0)
else:
  print(max(b))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n=int(input())
a=[]
x=np.full((n, n), -1)
p=[]
pp=[[0]*n for i in range(2**n)]
for i in range(n):
    a.append(int(input()))
    for j in range(a[i]):
      X,Y=(map(int,input().split()))
      x[i][X-1]=Y

def rev(x):
    if x ==1:
        return 0
    else:
        return 1
        
def dec2bin(target):
    amari=[]
    while target !=0:
        amari.append(target % 2)
        target = target //2
    if len(amari)!=n:
        while len(amari)!=n:
            amari.append(0)
    amari.reverse()
    return amari

for i in range(2**n):
    p.append(dec2bin(i))
b=[]
for i in range(2**n):
  flag=True
  for j in range(n):
      if p[i][j]==1:
        for k in range(n):
          if( x[j][k]==1 and p[i][k]==0)or (x[j][k]==0 and p[i][k]==1):
            flag=False
            break
        if flag==False:
          break
  if flag:
    b.append(p[i].count(1))
    
            
"""
                elif x[k][1]==0:
                    pp[i][x[k][0]-1]=0
                    
        elif p[i][j]==0:   
            for k in range(a[j]):
                if x[k][1]==0:
                    pp[i][x[k][0]-1]=1
                else:
                    pp[i][x[k][0]-1]=0
"""

if len(b)==0:
  print(0)
else:
  print(max(b))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n=int(input())
a=[]
x=np.full((n, n), -1)
p=[]
pp=[[0]*n for i in range(2**n)]
for i in range(n):
    a.append(int(input()))
    for j in range(a[i]):
      X,Y=(map(int,input().split()))
      x[i][X-1]=Y

        
def dec2bin(target):
    amari=[]
    while target !=0:
        amari.append(target % 2)
        target = target //2
    if len(amari)!=n:
        while len(amari)!=n:
            amari.append(0)
    amari.reverse()
    return amari

for i in range(2**n):
    p.append(dec2bin(i))
b=[]
for i in range(2**n):
  flag=True
  for j in range(n):
      if p[i][j]==1:
        for k in range(n):
          if( x[j][k]==1 and p[i][k]==0)or (x[j][k]==0 and p[i][k]==1):
            flag=False
            break
  if flag==True:
    b.append(p[i].count(1))
    
            
"""
                elif x[k][1]==0:
                    pp[i][x[k][0]-1]=0
                    
        elif p[i][j]==0:   
            for k in range(a[j]):
                if x[k][1]==0:
                    pp[i][x[k][0]-1]=1
                else:
                    pp[i][x[k][0]-1]=0
"""

if len(b)==0:
  print(0)
else:
  print(max(b))

Submission status: Time Limit Exceeded

Solution code:
import numpy as np
n=int(input())
a=[]
x=np.full((n, n), -1)
p=[]
pp=[[0]*n for i in range(2**n)]
for i in range(n):
    a.append(int(input()))
    for j in range(a[i]):
      X,Y=(map(int,input().split()))
      x[i][X-1]=Y

def rev(x):
    if x ==1:
        return 0
    else:
        return 1
        
def dec2bin(target):
    amari=[]
    while target !=0:
        amari.append(target % 2)
        target = target //2
    if len(amari)!=n:
        while len(amari)!=n:
            amari.append(0)
    amari.reverse()
    return amari

for i in range(2**n):
    p.append(dec2bin(i))
b=[]
for i in range(2**n):
  flag=True
  for j in range(n):
      if p[i][j]==1:
        for k in range(n):
          if( x[j][k]==1 and p[i][k]==0)or (x[j][k]==0 and p[i][k]==1):
            flag=False
  if flag==True:
    b.append(p[i].count(1))
    
            
"""
                elif x[k][1]==0:
                    pp[i][x[k][0]-1]=0
                    
        elif p[i][j]==0:   
            for k in range(a[j]):
                if x[k][1]==0:
                    pp[i][x[k][0]-1]=1
                else:
                    pp[i][x[k][0]-1]=0
"""

if len(b)==0:
  print(0)
else:
  print(max(b))

Submission status: Time Limit Exceeded

Solution code:

N = int(input())
#二次元配列
A = []

for i in range(N):
    a = int(input())
    A.append([])
    for j in range(a):
        x,y = map(int, input().split())
        A[i].append([x-1,y])
ans = 0
for i in range(2**N):
    #1:本当 0:嘘
    lie = [1]*N
    flg = 0
    for j in range(N):
        if (i>>j)&1:
            lie[j] = 0
    for j in range(N):
        for k in range(N):
            if j==k:
                continue
            #嘘をついているので、無視
            if lie[k]==0:
                continue
            #k番目の証言で
            for x,y in A[k]:
                if x==j and y!=lie[j]:
                    flg = 1
    if flg==0:
        ans = max(ans, sum(lie))

print(ans)

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env pypy3
import collections
import itertools as it
import math
#import numpy as np
 
n  = int(input())
#  = int(input())
#  = map(int, input().split())
#  = list(map(int, input().split()))i
xy = []
for _ in range(n):
    a = int(input())
    xy.append([tuple(map(int, input().split())) for _ in range(a)])
#
# c = collections.Counter()

for i in range(2 ** n): # 嘘つき・正直者の総当り
    is_honest = [not(bool(int(s))) for s in list('{:015b}'.format(i)[-n:])]
    is_ok = True
    for i, h in enumerate(list(is_honest)): # 人の総当り
        for x, y in xy[i]: # 証言の総当り
            if is_honest[i] == False:
                continue

            x = x - 1
            v = bool(int(y))
            
            #print(is_honest[x], bool(y), v, )
            if is_honest[x] == v:
                pass
            else:
                is_ok = False
    
    if is_ok:
        i#print(is_honest)
        print(sum(is_honest))
        break

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.buffer.readline

def main():
    n = int(input())
    #ビット全探索を行う
    import itertools
    li = list(itertools.product([0, 1], repeat=n)) # ０が不親切もの、１が親切もの

    #dd[i]:人iが人xをy（０なら不親切,１なら親切)だと思っていることを収納
    from collections import deque, defaultdict
    dd = {}
    for i in range(n):
        dd[i] = deque()
    for i in range(n):
        a = int(input())
        for j in range(a):
            x, y = map(int, input().split())
            dd[i].append((x-1, y))


    from copy import deepcopy
    max_sum = 0 #親切者の数の最大値
    for i in li: # i には親切者のタプルが入っている
        ppp = 0
        for ggg in i:
            ppp += ggg
        if ppp <= max_sum:
            continue
        sum_ = 0
        flag = True
        co = deepcopy(dd)
        for k in range(len(i)): #全員の証言が矛盾しないかを考える
            if i[k] == 0: # 不親切ものの場合
                continue
            else: #以下k人目の証言を考える
                sum_ += 1
                length = len(co[k])
                while co[k]:
                    x, y = co[k].popleft()
                    if i[x] != y: #証言と一致していない場合
                        flag = False
                        break
        if flag:
            max_sum = max(max_sum, sum_)

    print(max_sum)
            
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
input = sys.stdin.buffer.readline

def main():
    n = int(input())
    #ビット全探索を行う
    import itertools
    li = list(itertools.product([0, 1], repeat=n)) # ０が不親切もの、１が親切もの

    #dd[i]:人iが人xをy（０なら不親切,１なら親切)だと思っていることを収納
    from collections import deque, defaultdict
    dd = {}
    for i in range(n):
        dd[i] = deque()
    for i in range(n):
        a = int(input())
        for j in range(a):
            x, y = map(int, input().split())
            dd[i].append((x-1, y))


    from copy import deepcopy
    max_sum = 0 #親切者の数の最大値
    for i in li: # i には親切者のタプルが入っている
        ppp = 0
        for ggg in i:
            ppp += ggg
        if ppp <= max_sum:
            continue
        sum_ = 0
        co = deepcopy(dd)
        vv = 0
        for k in range(len(i)): #全員の証言が矛盾しないかを考える
            if i[k] == 0: # 不親切ものの場合
                continue
            else: #以下k人目の証言を考える
                sum_ += 1
                length = len(co[k])
                c = 0
                while co[k]:
                    x, y = co[k].popleft()
                    if i[x] != y: #証言と一致していない場合
                        break
                    else:
                        c+=1
                if c == length: #k人目の証言が全てあっている場合
                    vv += 1
        if vv == sum_:
            max_sum = max(max_sum, vv)

    print(max_sum)
            
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
def main():
    n = int(input())
    #ビット全探索を行う
    import itertools
    li = list(itertools.product([0, 1], repeat=n)) # ０が不親切もの、１が親切もの

    #dd[i]:人iが人xをy（０なら不親切,１なら親切)だと思っていることを収納
    from collections import deque, defaultdict
    dd = {}
    for i in range(n):
        dd[i] = deque()
    for i in range(n):
        a = int(input())
        for j in range(a):
            x, y = map(int, input().split())
            dd[i].append((x-1, y))


    from copy import deepcopy
    max_sum = 0 #親切者の数の最大値
    for i in li: # i には親切者のタプルが入っている
        ppp = 0
        for ggg in i:
            ppp += ggg
        if ppp <= max_sum:
            continue
        sum_ = 0
        co = deepcopy(dd)
        vv = 0
        for k in range(len(i)): #全員の証言が矛盾しないかを考える
            if i[k] == 0: # 不親切ものの場合
                continue
            else: #以下k人目の証言を考える
                sum_ += 1
                length = len(co[k])
                c = 0
                while co[k]:
                    x, y = co[k].popleft()
                    if i[x] != y: #証言と一致していない場合
                        break
                    else:
                        c+=1
                if c == length: #k人目の証言が全てあっている場合
                    vv += 1
        if vv == sum_:
            max_sum = max(max_sum, vv)

    print(max_sum)
            
if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
#ビット全探索を行う
import itertools
li = list(itertools.product([0, 1], repeat=n)) # ０が不親切もの、１が親切もの

#dd[i]:人iが人xをy（０なら不親切,１なら親切)だと思っていることを収納
from collections import deque, defaultdict
dd = defaultdict(lambda:deque())
for i in range(n):
    a = int(input())
    for j in range(a):
        x, y = map(int, input().split())
        dd[i].append((x-1, y))


from copy import deepcopy
max_sum = 0 #親切者の数の最大値
for i in li: # i には親切者のタプルが入っている
    ppp = 0
    for ggg in i:
        ppp += ggg
    if ppp <= max_sum:
        continue
    sum_ = 0
    co = deepcopy(dd)
    vv = 0
    for k in range(len(i)): #全員の証言が矛盾しないかを考える
        if i[k] == 0: # 不親切ものの場合
            continue
        else: #以下k人目の証言を考える
            sum_ += 1
            length = len(co[k])
            c = 0
            while co[k]:
                x, y = co[k].popleft()
                if i[x] != y: #証言と一致していない場合
                    break
                else:
                    c+=1
            if c == length: #k人目の証言が全てあっている場合
                vv += 1
    if vv == sum_:
        max_sum = max(max_sum, vv)

print(max_sum)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())
#ビット全探索を行う
import itertools
li = list(itertools.product([0, 1], repeat=n)) # ０が不親切もの、１が親切もの

#dd[i]:人iが人xをy（０なら不親切,１なら親切)だと思っていることを収納
from collections import deque, defaultdict
dd = defaultdict(lambda:deque())
for i in range(n):
    a = int(input())
    for j in range(a):
        x, y = map(int, input().split())
        dd[i].append((x-1, y))


from copy import deepcopy
max_sum = 0 #親切者の数の最大値
for i in li: # i には親切者のタプルが入っている
    sum_ = 0
    co = deepcopy(dd)
    vv = 0
    for k in range(len(i)): #全員の証言が矛盾しないかを考える
        if i[k] == 0: # 不親切ものの場合
            continue
        else: #以下k人目の証言を考える
            sum_ += 1
            length = len(co[k])
            c = 0
            while co[k]:
                x, y = co[k].popleft()
                if i[x] != y: #証言と一致していない場合
                    break
                else:
                    c+=1
            if c == length: #k人目の証言が全てあっている場合
                vv += 1
    if vv == sum_:
        max_sum = max(max_sum, vv)

print(max_sum)

Submission status: Time Limit Exceeded

Solution code:
n = int(input())

XY = []
for i in range(n):
    a = int(input())
    xy = []
    for j in range(a):
        xy.append(list(map(int, input().split())))
    
    XY.append(xy)
    
def check(i, xiyj, HoU):
    # 矛盾したらFalse 正直者と仮定した証言より 正直&正直者と仮定されている / 不親切&不親切と仮定されている True
    if ((i >> xiyj) & 1) ^ HoU:
        return False

    return True
    
max_honest = 0
for i in range(2 ** len(XY)):
    count = 0
    honest = [0] * len(XY)
    is_contradiction = True
    for j in range(len(XY)):
        # 正直者と仮定したときだけ採用
        if not ((i >> j) & 1): continue
        for k in range(len(XY[j])):
            xiyj = XY[j][k][0] - 1
            HoU = XY[j][k][1]
            
            if not check(i, xiyj, HoU):
                is_contradiction = False

    if is_contradiction:
        for j in range(len(XY)):
            if ((i >> j) & 1): count+=1 
                
        if count > max_honest:
            max_honest =count
            
print(max_honest)

Submission status: Time Limit Exceeded

Solution code:
from copy import copy

def listmake(n, lists, tmp=[], ans=[]):
    if n == 0:
        ans.append(tmp)
        return ans
        
    for i in lists:   
        a = copy(lists)
        a.remove(i)
        ans = listmake(n - 1, a, tmp + [i], ans)
    return ans 


N = int(input())
X = [[-1 for i in range(N)] for i in range(N)]

for i in range(N):
    a = int(input())
    for j in range(a):
        x, y = map(int, input().split())
        X[i][x - 1] = y

for i in range(N):
    ans = True
    if i == 0:
        for k in range(N):
            for s in range(N):
                if X[k][s] == 0:
                    ans = False
        if ans:
            print(N - i)
            exit()
        
    else:
        for j in listmake(i, [k for k in range(N)]):
            ans = True
            for k in range(N):
                if k not in j:
                    for s in range(N):
                        if s in j:
                            if X[k][s] == 1:
                                ans = False
                        else:
                            if X[k][s] == 0:
                                ans = False
                    if not ans:
                        break
                if not ans:
                    break
            if ans:
                print(N - i)
                exit()
                            
print(0)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
path = []
ans = 0
ap = path.append
for i in range(N):
    A = int(input())
    ap([])
    for j in range(A):
        x, y = map(int,input().split())
        x -= 1
        path[-1].append((x, y))
for i in range(1<<N):
    i |= (1<<N)
    judge = True
    for j in range(N):
        if (1<<j) & i:
            for k in range(len(path[j])):
                if path[j][k][1] != int(bin(i)[-path[j][k][0] - 1]):
                    judge = False
    if judge:
        if ans < bin(i).count("1") - 1:
            ans = bin(i).count("1") - 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
N = int(input())
path = []
ans = 0
for i in range(N):
    A = int(input())
    path.append([])
    for j in range(A):
        x, y = map(int,input().split())
        x -= 1
        path[-1].append((x, y))
for i in range(1<<N):
    i |= (1<<N)
    judge = True
    for j in range(N):
        if (1<<j) & i:
            for k in range(len(path[j])):
                if path[j][k][1] != int(bin(i)[-path[j][k][0] - 1]):
                    judge = False
    if judge:
        if ans < bin(i).count("1") - 1:
            ans = bin(i).count("1") - 1
print(ans)

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
readline = sys.stdin.readline
N = int(readline())

testimonies = [[[], []] for _ in range(N)]
# testimonies = [[-1 for _ in range(N)] for _ in range(N)]
for i in range(N):
    A = int(readline())
    for _ in range(A):
        x, y = map(int, readline().rstrip().split())
        testimonies[i][y].append(x-1)
        # testimonies[i][x-1] = y

def check(honest_persons):
    """矛盾がないか検証する"""
    honest_checked = set(honest_persons)  # 宛先を確認済みの正直者の人
    honest_stack = deque(honest_persons)  # 宛先を確認する正直者の人の待ち行列
    honest, liers = honest_persons[:], []  # 正直者の人, 不親切な人

    # 正直者の人の証言も元に、正直者の人/不親切な人を追加していく
    while len(honest_stack) > 0:
        honest_person = honest_stack.popleft()
        honest_checked.add(honest_person)
        next_honest_persons = testimonies[honest_person][1]

        # 検証済み以外の人をstackする
        for person in next_honest_persons:
            if person not in honest_checked:
                honest_stack.append(person)

        honest += testimonies[honest_person][1]
        liers += testimonies[honest_person][0]

    # 矛盾がなければOK
    if len(set(honest) & set(liers)) == 0:
        return True
    else:
        return False

def main():
    # bit全探索する
    ans = 0
    has_checked = []
    for i in range(1, 2**N):
        comb = bin(i)[2:].zfill(N)
        honest_persons = [p for p, c in enumerate(comb) if c == '1']
        
        flag = False
        for checked in has_checked:
            if checked < set(honest_persons):
                flag = True
                break
        
        if flag:
            continue

        if check(honest_persons):
            ans = max(ans, sum(list(map(int, list(comb)))))
        else:
            has_checked.append(set(honest_persons))

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
readline = sys.stdin.readline
N = int(readline())

testimonies = [[[], []] for _ in range(N)]
for i in range(N):
    A = int(readline())
    for _ in range(A):
        x, y = map(int, readline().rstrip().split())
        testimonies[i][y].append(x-1)

def check(honest_persons):
    """矛盾がないか検証する"""
    honest_checked = set(honest_persons)  # 宛先を確認済みの正直者の人
    honest_stack = deque(honest_persons)  # 宛先を確認する正直者の人の待ち行列
    honest, liers = honest_persons[:], []  # 正直者の人, 不親切な人

    # 正直者の人の証言も元に、正直者の人/不親切な人を追加していく
    while len(honest_stack) > 0:
        honest_person = honest_stack.popleft()
        honest_checked.add(honest_person)
        next_honest_persons = testimonies[honest_person][1]

        # 検証済み以外の人をstackする
        for person in next_honest_persons:
            if person not in honest_checked:
                honest_stack.append(person)

        honest += testimonies[honest_person][1]
        liers += testimonies[honest_person][0]

        if len(set(honest) & set(liers)) != 0:
            return False

    return True

def main():
    # bit全探索する
    ans = 0
    has_checked = []
    for i in range(1, 2**N):
        comb = bin(i)[2:].zfill(N)
        honest_persons = []
        for p, c in enumerate(comb):
            if c == '1':
                honest_persons.append(p)
        
        flag = False
        for checked in has_checked:
            if checked < set(honest_persons):
                flag = True
                break
        
        if flag:
            continue

        if check(honest_persons):
            ans = max(ans, sum(list(map(int, list(comb)))))
        else:
            has_checked.append(set(honest_persons))

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
readline = sys.stdin.readline
N = int(readline())

testimonies = [[[], []] for _ in range(N)]
for i in range(N):
    A = int(readline())
    for _ in range(A):
        x, y = map(int, readline().rstrip().split())
        testimonies[i][y].append(x-1)

def check(honest_persons):
    """矛盾がないか検証する"""
    honest_checked = set(honest_persons)  # 宛先を確認済みの正直者の人
    honest_stack = deque(honest_persons)  # 宛先を確認する正直者の人の待ち行列
    honest, liers = set(honest_persons), set()  # 正直者の人, 不親切な人

    # 正直者の人の証言も元に、正直者の人/不親切な人を追加していく
    while len(honest_stack) > 0:
        honest_person = honest_stack.popleft()
        honest_checked.add(honest_person)
        next_honest_persons = testimonies[honest_person][1]

        # 検証済み以外の人をstackする
        for person in next_honest_persons:
            if person not in honest_checked:
                honest_stack.append(person)

        honest |= set(testimonies[honest_person][1])
        liers |= set(testimonies[honest_person][0])

    # 矛盾がなければOK
    if len(honest & liers) == 0:
        return True
    else:
        return False

def main():
    # bit全探索する
    ans = 0
    has_checked = []
    for i in range(1, 2**N):
        comb = bin(i)[2:].zfill(N)
        honest_persons = []
        for p, c in enumerate(comb):
            if c == '1':
                honest_persons.append(p)
        
        flag = False
        for checked in has_checked:
            if checked < set(honest_persons):
                flag = True
                break
        
        if flag:
            continue

        if check(honest_persons):
            ans = max(ans, sum(list(map(int, list(comb)))))
        else:
            has_checked.append(set(honest_persons))

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
readline = sys.stdin.readline
N = int(readline())

testimonies = [[[], []] for _ in range(N)]
for i in range(N):
    A = int(readline())
    for _ in range(A):
        x, y = map(int, readline().rstrip().split())
        testimonies[i][y].append(x-1)

def check(honest_persons):
    """矛盾がないか検証する"""
    honest_checked = set(honest_persons)  # 宛先を確認済みの正直者の人
    honest_stack = deque(honest_persons)  # 宛先を確認する正直者の人の待ち行列
    honest, liers = honest_persons[:], []  # 正直者の人, 不親切な人

    # 正直者の人の証言も元に、正直者の人/不親切な人を追加していく
    while len(honest_stack) > 0:
        honest_person = honest_stack.popleft()
        honest_checked.add(honest_person)
        next_honest_persons = testimonies[honest_person][1]

        # 検証済み以外の人をstackする
        for person in next_honest_persons:
            if person not in honest_checked:
                honest_stack.append(person)

        honest += testimonies[honest_person][1]
        liers += testimonies[honest_person][0]

    # 矛盾がなければOK
    if len(set(honest) & set(liers)) == 0:
        return True
    else:
        return False

def main():
    # bit全探索する
    ans = 0
    has_checked = []
    for i in range(1, 2**N):
        comb = bin(i)[2:].zfill(N)
        honest_persons = []
        for p, c in enumerate(comb):
            if c == '1':
                honest_persons.append(p)
        
        flag = False
        for checked in has_checked:
            if checked < set(honest_persons):
                flag = True
                break
        
        if flag:
            continue

        if check(honest_persons):
            ans = max(ans, sum(list(map(int, list(comb)))))
        else:
            has_checked.append(set(honest_persons))

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
readline = sys.stdin.readline
N = int(readline())

testimonies = [[[], []] for _ in range(N)]
for i in range(N):
    A = int(readline())
    for _ in range(A):
        x, y = map(int, readline().rstrip().split())
        testimonies[i][y].append(x-1)

def check(honest_persons):
    """矛盾がないか検証する"""
    honest_checked = set(honest_persons)  # 宛先を確認済みの正直者の人
    honest_stack = deque(honest_persons)  # 宛先を確認する正直者の人の待ち行列
    honest, liers = honest_persons, []  # 正直者の人, 不親切な人

    # 正直者の人の証言も元に、正直者の人/不親切な人を追加していく
    while len(honest_stack) > 0:
        honest_person = honest_stack.popleft()
        honest_checked.add(honest_person)
        next_honest_persons = testimonies[honest_person][1]

        # 検証済み以外の人をstackする
        for person in next_honest_persons:
            if person not in honest_checked:
                honest_stack.append(person)

        honest += testimonies[honest_person][1]
        liers += testimonies[honest_person][0]

    # 矛盾がなければOK
    if len(set(honest) & set(liers)) == 0:
        return True
    else:
        return False

def main():
    # bit全探索する
    ans = 0
    for i in range(1, 2**N):
        comb = bin(i)[2:].zfill(N)
        honest_persons = []
        for p, c in enumerate(comb):
            if c == '1':
                honest_persons.append(p)
        if check(honest_persons):
            ans = max(ans, sum(list(map(int, list(comb)))))

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
import sys
from collections import deque
readline = sys.stdin.readline
N = int(readline())

# testimonies = {}
testimonies = [[[], []] for _ in range(N)]
for i in range(N):
    A = int(readline())
    # testimonies[i] = [[], []]
    for _ in range(A):
        x, y = map(int, readline().rstrip().split())
        testimonies[i][y].append(x-1)

def check(honest_persons):
    """矛盾がないか検証する"""
    honest_checked = set()  # 宛先を確認済みの正直者の人
    honest_stack = deque(honest_persons)  # 宛先を確認する正直者の人の待ち行列
    honest, liers = honest_persons, []  # 正直者の人, 不親切な人

    # 正直者の人の証言も元に、正直者の人/不親切な人を追加していく
    while len(honest_stack) > 0:
        honest_person = honest_stack.popleft()
        honest_checked.add(honest_person)
        next_honest_persons = testimonies[honest_person][1]

        # 検証済み以外の人をstackする
        for person in next_honest_persons:
            if person not in honest_checked:
                honest_stack.append(person)

        honest += testimonies[honest_person][1]
        liers += testimonies[honest_person][0]

    # 矛盾がなければOK
    if len(set(honest) & set(liers)) == 0:
        return True
    else:
        return False

def main():
    # bit全探索する
    ans = 0
    for i in range(1, 2**N):
        comb = bin(i)[2:].zfill(N)
        honest_persons = []
        for p, c in enumerate(comb):
            if c == '1':
                honest_persons.append(p)
        if check(honest_persons):
            ans = max(ans, sum(list(map(int, list(comb)))))

    print(ans)

if __name__ == '__main__':
    main()