Problem:

Problem G: True Liars

After having drifted about in a small boat for a couple of days, Akira Crusoe Maeda was finally cast ashore on a foggy island. Though he was exhausted and despaired, he was still fortunate to remember a legend of the foggy island, which he had heard from patriarchs in his childhood. This must be the island in the legend.

In the legend, two tribes have inhabited the island, one is divine and the other is devilish; once members of the divine tribe bless you, your future is bright and promising, and your soul will eventually go to Heaven; in contrast, once members of the devilish tribe curse you, your future is bleak and hopeless, and your soul will eventually fall down to Hell.

In order to prevent the worst-case scenario, Akira should distinguish the devilish from the divine. But how? They looked exactly alike and he could not distinguish one from the other solely by their appearances. He still had his last hope, however. The members of the divine tribe are truth-tellers, that is, they always tell the truth and those of the devilish tribe are liars, that is, they always tell a lie.

He asked some of the whether or not some are divine. They knew one another very much and always responded to him "faithfully" according to their individual natures (i.e., they always tell the truth or always a lie). He did not dare to ask any other forms of questions, since the legend says that a devilish member would curse a person forever when he did not like the question. He had another piece of useful information: the legend tells the populations of both tribes. These numbers in the legend are trustworthy since everyone living on this island is immortal and none have ever been born at least these millennia.

You are a good computer programmer and so requested to help Akira by writing a program that classifies the inhabitants according to their answers to his inquiries. 

Input

The input consists of multiple data sets, each in the following format:

n p1 p2
x1 y1 a1
x2 y2 a2
...
xi yi ai
...
xn yn an

The first line has three non-negative integers n, p1, and p2. n is the number of questions Akira asked. p1 and p2 are the populations of the divine and devilish tribes, respectively, in the legend. Each of the following n lines has two integers xi, yi and one word ai. xi and yi are the identification numbers of inhabitants, each of which is between 1 and p1 + p2, inclusive. ai is either "yes", if the inhabitant xi said that the inhabitant yi was a member of the divine tribe, or "no", otherwise. Note that xi and yi can be the same number since "are you a member of the divine tribe?" is a valid question. Note also that two lines may have the same x's and y's since Akira was very upset and might have asked the same question to the same one more than once.

You may assume that n is less than 1000 and that p1 and p2 are less than 300. A line with three zeros, i.e., "0 0 0", represents the end of the input. You can assume that each data set is consistent and no contradictory answers are included. 

Output

For each data set, if it includes sufficient information to classify all the inhabitants, print the identification numbers of all the divine ones in ascending order, one in a line. In addition, following the output numbers, print "end" in a line. Otherwise, i.e., if a given data set does not include sufficient information to identify all the divine members, print "no" in a line.

Sample Input

2 1 1
1 2 no
2 1 no
3 2 1
1 1 yes
2 2 yes
3 3 yes
2 2 1
1 2 yes
2 3 no
5 4 3
1 2 yes
1 3 no
4 5 yes
5 6 yes
6 7 no
0 0 0

Output for the Sample Input

no
no
1
2
end
3
4
5
6
end



Sample input:
2 1 1
1 2 no
2 1 no
3 2 1
1 1 yes
2 2 yes
3 3 yes
2 2 1
1 2 yes
2 3 no
5 4 3
1 2 yes
1 3 no
4 5 yes
5 6 yes
6 7 no
0 0 0


Sample output:
no
no
1
2
end
3
4
5
6
end

Submission status: Wrong Answer

Solution code:
from collections import defaultdict


class UnionFind():
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n

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

    def unite(self, x, y):
        x, y = self.find(x), self.find(y)

        if x == y:
            return

        if self.rank[x] < self.rank[y]:
            self.parent[x] = y
        else:
            self.parent[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1


while True:
    n, p1, p2 = (int(s) for s in input().split())
    if not n:
        break

    p = p1 + p2
    tree = UnionFind(p * 2)
    unions = defaultdict(list)

    for i in range(n):
        xs, ys, a = input().split()
        x, y = int(xs) - 1, int(ys) - 1
        if a == 'yes':
            tree.unite(x, y)
            tree.unite(x + p, y + p)
        else:
            tree.unite(x, y + p)
            tree.unite(x + p, y)

    for i in range(p):
        unions[tree.find(i)].append(i)
    roots = []
    sides = []
    diffs = []
    rest = p1
    for i in range(p):
        if i in unions:
            member_len, backside_len = len(unions[i]), len(unions[i + p])
            if member_len == backside_len:
                rest = -1
                break
            elif member_len < backside_len:
                diff = backside_len - member_len
                rest -= member_len
                sides.append(0)
            else:
                diff = member_len - backside_len
                sides.append(1)
                rest -= backside_len
            roots.append(i)
            diffs.append(diff)
    if rest < 0:
        print('no')
        continue

    dp = [[1] + [0] * rest for i in range(len(roots) + 1)]

    for i in reversed(range(len(roots))):
        for j in range(1, rest + 1):
            if j < diffs[i]:
                if dp[i + 1][j]:
                    dp[i][j] = 1
                else:
                    dp[i][j] = 0
            else:
                if dp[i + 1][j] and dp[i + 1][j - diffs[i]]:
                    dp[i][j] = 3
                elif dp[i + 1][j - diffs[i]]:
                    dp[i][j] = 2
                elif dp[i + 1][j]:
                    dp[i][j] = 1
                else:
                    dp[i][j] = 0

    divines = []
    for i in range(len(roots)):
        if dp[i][rest] == 1:
            divines.extend(unions[roots[i] + p * sides[i]])
        elif dp[i][rest] == 2:
            divines.extend(unions[roots[i] + p * (1 - sides[i])])
            rest -= diffs[i]
        else:
            print('no')
            break
    else:
        divines.sort()
        for divine in divines:
            print(divine + 1)
        print('end')

Submission status: Wrong Answer

Solution code:
#! /usr/bin/python
# -*- coding: utf-8 -*-

def main():
    # input
    while True:
        # p1:devine num.
        # p2:devillish num.
        (n, p1, p2) = map(int, raw_input().split())
        if n == 0:
            break
        data = [convertSays(raw_input().split()) for x in xrange(n)]

        # output
        # devine member in ascending order. -> 'end'
        # if there is no sufficient iformation, putting 'no'
        for x in solve(data, p1, p2):
            print(x)

def convertSays(data):
    num = map(int, data[:-1])
    return num + data[-1:]

def solve(data, p1, p2):
    # [((groupA), (groupB)), ((groupXX), (groupXX))]
    forest = []

    def searchForestYes(a, b):
        for i, x in enumerate(forest):
            if a in x[0]:
                x[0].add(b)
                forest[i] = (x[0], x[1])
                return
            elif a in x[1]:
                x[1].add(b)
                forest[i] = (x[0], x[1])
                return
        else:
            forest.append((set([a,b]),set([])))

    def searchForestNo(a, b):
        for i, x in enumerate(forest):
            if a in x[0]:
                x[1].add(b)
                forest[i] = (x[0], x[1])
                return
            elif a in x[1]:
                x[0].add(b)
                forest[i] = (x[1], x[0])
                return
        else:
            forest.append((set([a]),set([b])))

    # グループ分け
    for x in data:
        if x[2] == 'yes':
            searchForestYes(*x[:-1])
        elif x[2] == 'no':
            searchForestNo(*x[:-1])

    return judge(forest, p1, p2)

def judge(forest, p1, p2):

    # 組み合わせを生成
    def comb(forest):
        if not forest:
            yield ()
            return

        for x in forest[0]:
            for y in comb(forest[1:]):
                yield tuple(x) + y

    def judge_(gen):
        cntDic = {x:len(x) for x in gen}
        p1_cnt = filter(lambda x:cntDic[x] == p1, cntDic)
        if len(p1_cnt) == 1:
            return sorted(p1_cnt[0]) + ['end']
        else:
            return ['no']

    gen = comb(forest)
    return judge_(gen)

def test():
    p1 , p2 = 4, 3
    data = [[1,2,'yes'],
            [1,3,'no'],
            [4,5,'yes'],
            [5,6,'yes'],
            [6,7,'no']]
    for x in solve(data, p1, p2):
        print(x)
if __name__=='__main__':
    # test()
    main()

Submission status: Wrong Answer

Solution code:
#! /usr/bin/python
# -*- coding: utf-8 -*-

def main():
    # input
    while True:
        # p1:devine num.
        # p2:devillish num.
        (n, p1, p2) = map(int, raw_input().split())
        if n == 0 and p1 == 0 and p2 == 0:
            break
        elif p1 == 0:
            print('end')
            [raw_input() for x in xrange(n)]
        elif p2 == 0:
            for x in xrange(p1):
                print(x + 1)
            print('end')
            [raw_input() for x in xrange(n)]

        elif n == 0:
            print('no')

        else:
            data = [convertSays(raw_input().split()) for x in xrange(n)]

            # output
            # devine member in ascending order. -> 'end'
            # if there is no sufficient iformation, putting 'no'
            for x in solve(data, p1, p2):
                print(x)

def convertSays(data):
    num = map(int, data[:-1])
    return num + data[-1:]

def solve(data, p1, p2):
    yes = {}
    no = {}

    def groupdYesNo(a, b, say):
        if say == 'yes':
            if a in yes:
                buf = yes[a]
                buf.add(b)
                yes[a] = buf
            else:
                yes[a] = set([b])

            if b in yes:
                buf = yes[b]
                buf.add(a)
                yes[b] = buf
            else:
                yes[b] = set([a])

        elif say == 'no':
            if a in no:
                buf = no[a]
                buf.add(b)
                no[a] = buf
            else:
                no[a] = set([b])
            if b in no:
                buf = no[b]
                buf.add(a)
                no[b] = buf
            else:
                no[b] = set([a])

    def groupdMember(yes, no):
        # グループをまとめる
        seen = [set()]
        def groupdMember(buf, buf_2):
            new_buf = set()
            new_buf2 = buf_2

            if len(filter(lambda x:x not in seen[0],buf))== 0:
                return buf, buf_2
            for x in buf:
                new_buf.add(x)
                if x in yes:
                    for y in yes[x]:
                        new_buf.add(y)
                        if y in yes:
                            new_buf = new_buf.union(yes[y])

            for x in new_buf:
                if x in no:
                    new_buf2 = new_buf2.union(no[x])

            seen[0] = seen[0].union(new_buf)
            return groupdMember(new_buf2, new_buf)

        ret = [groupdMember(set([x]), set()) for x in yes]
        ret2 = [groupdMember(set([x]), set()) for x in no]
        return filter(lambda x:len(x[0]) + len(x[1]) > 1, ret + ret2)

    # グループ分け
    [groupdYesNo(*x) for x in data]
    group = groupdMember(yes, no)

    if len(group) == 0:
        return ['no']
    return judge(group, p1, p2)

def numForest(forest):
    return [(len(x[0]), len(x[1])) for x in forest]

def judge(forest, p1, p2):
    num_forest = numForest(forest)
    ans = []

    # 正直者がdevine_numの場合の
    # 組み合わせの数を返す
    @memoize
    def makeComb(forest_i, devine_num):
        if devine_num < 0:
            return 0
        if forest_i == 0:
            left = [num_forest[forest_i][0]].count(devine_num)
            right = [num_forest[forest_i][1]].count(devine_num)
        else:
            left = makeComb(forest_i - 1, devine_num - num_forest[forest_i][0])
            right = makeComb(forest_i - 1, devine_num -  num_forest[forest_i][1])

        # 組み合わせが1の場合の解を保存する
        if (left + right) == 1:
            ans.append((left, right))

        return left + right

    def makeDevine(ans, forest):
        buf = []
        for i, x in enumerate(ans):
            if x == (0, 1):
                buf += list(forest[i][1])
            else:
                buf += list(forest[i][0])
        return sorted(buf)

    devine_comb = makeComb(len(num_forest) - 1, p1)

    if devine_comb == 1:
        return makeDevine(ans, forest) + ['end']
    else:
        return ['no']

# メモ化関数
def memoize(f):
    cache = {}
    def helper(*args):
        if args not in cache:
            cache[args] = f(*args)
        return cache[args]
    return helper

def test():
    p1 , p2 = 8, 3
    data = [[1,2,'yes'],
            [1,8,'yes'],
            [1,3,'no'],
            [4,5,'yes'],
            [5,6,'yes'],
            [6,7,'no'],
            [9,10,'no'],
            [9,11,'no'],
            [3,7,'yes']]
    for x in solve(data, p1, p2):
        print(x)
if __name__=='__main__':
    # test()
    main()
testdata = """
208 101 100
94 31 no
179 115 no
136 60 no
147 26 yes
43 17 no
123 92 yes
13 77 no
126 32 no
176 76 yes
128 137 yes
36 102 no
102 149 yes
41 45 yes
15 62 yes
191 116 no
69 201 yes
36 123 no
103 102 no
48 115 yes
59 114 no
191 45 no
51 122 yes
84 168 yes
130 51 no
154 148 no
169 198 no
7 42 no
161 134 yes
6 117 no
64 111 no
57 163 yes
23 171 yes
18 91 yes
81 10 yes
163 39 yes
46 189 yes
139 80 no
143 73 yes
171 133 yes
95 153 yes
25 150 no
136 4 no
15 52 yes
21 13 no
196 93 yes
22 124 yes
127 59 yes
161 150 no
103 69 no
156 46 yes
39 182 yes
173 49 no
8 91 yes
29 99 yes
60 184 no
190 73 yes
135 71 no
24 152 no
181 29 yes
186 88 no
71 113 no
28 82 no
156 110 no
128 170 no
26 55 yes
155 82 no
118 1 yes
37 104 no
108 83 no
35 19 no
140 126 yes
117 11 no
40 3 no
181 145 yes
97 108 yes
125 146 yes
157 164 yes
8 40 no
85 63 no
7 77 no
16 151 no
55 21 no
64 93 yes
159 84 yes
148 142 yes
197 42 no
165 6 no
50 105 no
96 20 no
105 121 yes
201 83 yes
199 197 yes
98 4 yes
36 141 yes
54 194 yes
90 14 yes
153 70 yes
18 97 no
134 127 yes
101 167 no
125 68 no
12 86 no
174 162 no
78 177 yes
168 9 yes
88 130 yes
196 162 yes
164 192 no
189 74 no
54 158 yes
160 198 yes
132 62 yes
68 100 no
195 180 yes
193 144 yes
72 50 yes
65 118 no
41 151 yes
119 195 yes
79 172 no
120 53 no
61 165 no
75 74 no
61 24 no
66 67 yes
178 94 yes
167 170 yes
135 138 no
58 176 no
87 114 yes
33 146 no
47 131 no
56 187 no
127 108 yes
14 166 yes
159 2 yes
30 96 yes
186 94 no
166 190 yes
153 153 yes
27 28 yes
142 188 yes
32 187 yes
106 178 yes
121 89 yes
179 157 yes
66 89 yes
185 70 no
98 147 yes
12 109 no
85 160 no
90 113 no
182 44 no
188 22 no
180 199 yes
141 183 yes
193 87 no
140 23 no
200 109 yes
5 173 yes
112 137 no
194 2 yes
25 138 no
81 131 yes
132 110 yes
33 122 no
158 120 no
79 49 no
149 35 yes
3 34 no
11 48 yes
37 175 no
129 43 no
9 92 no
124 53 yes
111 143 yes
45 201 no
38 16 no
80 112 yes
44 101 yes
38 200 no
192 174 no
145 175 no
20 119 no
10 177 no
75 47 no
116 58 yes
78 139 yes
63 172 no
154 72 yes
99 65 no
1 31 yes
183 107 no
106 57 yes
152 104 no
107 5 no
30 68 yes
185 67 yes
95 135 yes
19 169 no
155 52 no
178 86 yes
27 184 no
129 100 no
22 118 yes
144 56 no
34 76 no
133 71 no
0 0 0
"""
#

Submission status: Wrong Answer

Solution code:
#! /usr/bin/python
# -*- coding: utf-8 -*-

from collections import defaultdict

def main():
    # input
    while True:
        # p1:devine num.
        # p2:devillish num.
        (n, p1, p2) = map(int, raw_input().split())
        if n == 0 and p1 == 0 and p2 == 0:
            break
        elif p1 == 0:
            print('end')
            [raw_input() for x in xrange(n)]
        elif p2 == 0:
            for x in xrange(p1):
                print(x + 1)
            print('end')
            [raw_input() for x in xrange(n)]

        elif n == 0:
            print('no')

        else:
            data = [convertSays(raw_input().split()) for x in xrange(n)]

            # output
            # devine member in ascending order. -> 'end'
            # if there is no sufficient iformation, putting 'no'
            for x in solve(data, p1, p2):
                print(x)

def convertSays(data):
    num = map(int, data[:-1])
    return num + data[-1:]

def solve(data, p1, p2):
    yes = defaultdict(set)
    no = defaultdict(set)

    def groupdYesNo(a, b, say):
        if say == 'yes':
            yes[a].update(set([b]))
            yes[b].update(set([a]))

            buf = yes[a].union(yes[b])
            yes[a] = yes[b] = buf

        elif say == 'no':
            no[a].update(set([b]))
            for x in no[a]:
                no[x].update(set([a]))
            no[b].update(set([a]))
            for x in no[b]:
                no[x].update(set([b]))

    def groupdMember(yes, no):
        # グループをまとめる
        seen = [set()]
        def groupdMember(buf, buf_2):
            new_buf = set()
            new_buf2 = buf_2

            if len(filter(lambda x:x not in seen[0],buf))== 0:
                return buf, buf_2
            for x in buf:
                new_buf.add(x)
                if x in yes:
                    for y in yes[x]:
                        new_buf.add(y)
                        if y in yes:
                            new_buf = new_buf.union(yes[y])

            for x in new_buf:
                if x in no:
                    new_buf2 = new_buf2.union(no[x])

            seen[0] = seen[0].union(new_buf)
            return groupdMember(new_buf2, new_buf)

        ret = [groupdMember(set([x]), set()) for x in yes]
        ret2 = [groupdMember(set([x]), set()) for x in no]
        ret3 = filter(lambda x:len(x[0]) + len(x[1]) > 1, ret + ret2)

        return ret3

    # グループ分け
    [groupdYesNo(*x) for x in data]
    group = groupdMember(yes, no)

    if len(group) == 0:
        return ['no']
    return judge(group, p1, p2)

def numForest(forest):
    return [(len(x[0]), len(x[1])) for x in forest]

# メモ化関数
def memoize(f):
    cache = {}
    def helper(*args):
        if args not in cache:
            cache[args] = f(*args)
        return cache[args]
    return helper

def judge(forest, p1, p2):
    num_forest = numForest(forest)
    ans = range(1000)

    # 正直者がdevine_numの場合の
    # 組み合わせの数を返す
    @memoize
    def makeComb(forest_i, devine_num):
        if devine_num < 0:
            return 0
        if forest_i == 0:
            left = [num_forest[forest_i][0]].count(devine_num)
            right = [num_forest[forest_i][1]].count(devine_num)
        else:
            left = makeComb(forest_i - 1, devine_num - num_forest[forest_i][0])
            right = makeComb(forest_i - 1, devine_num -  num_forest[forest_i][1])

        # 組み合わせが1の場合の解を保存する
        if (left + right) == 1:
            ans[forest_i]= (left, right)
            return left + right
        elif (left + right) > 1:
            return 2
        else:
            return 0

    def makeDevine(ans, forest):
        buf = []
        for i, x in enumerate(ans[:len(forest)]):
            if x == (0, 1):
                buf += list(forest[i][1])
            else:
                buf += list(forest[i][0])
        return sorted(buf)

    devine_comb = makeComb(len(num_forest) - 1, p1)
    if devine_comb == 1:
        return makeDevine(ans, forest) + ['end']
    else:
        return ['no']

def test():
    p1 , p2 = 8, 3
    data = [[1,2,'yes'],
            [1,8,'yes'],
            [1,3,'no'],
            [4,5,'yes'],
            [5,6,'yes'],
            [6,7,'no'],
            [9,10,'no'],
            [9,11,'no'],
            [3,7,'yes']]
    for x in solve(data, p1, p2):
        print(x)

if __name__=='__main__':
    # test()
    main()

Submission status: Memory Limit Exceeded

Solution code:
#! /usr/bin/python
# -*- coding: utf-8 -*-

def main():
    # input
    while True:
        # p1:devine num.
        # p2:devillish num.
        (n, p1, p2) = map(int, raw_input().split())
        if n == 0 and p1 == 0 and p2 == 0:
            break
        data = [convertSays(raw_input().split()) for x in xrange(n)]

        # output
        # devine member in ascending order. -> 'end'
        # if there is no sufficient iformation, putting 'no'
        for x in solve(data, p1, p2):
            print(x)

def convertSays(data):
    num = map(int, data[:-1])
    return num + data[-1:]

def solve(data, p1, p2):
    # [((groupA), (groupB)), ((groupXX), (groupXX))]
    forest = []

    def searchForestYes(a, b):
        for i, x in enumerate(forest):
            if a in x[0]:
                x[0].add(b)
                forest[i] = (x[0], x[1])
                return
            elif a in x[1]:
                x[1].add(b)
                forest[i] = (x[0], x[1])
                return
        else:
            forest.append((set([a,b]),set([])))

    def searchForestNo(a, b):
        for i, x in enumerate(forest):
            if a in x[0]:
                x[1].add(b)
                forest[i] = (x[0], x[1])
                return
            elif a in x[1]:
                x[0].add(b)
                forest[i] = (x[1], x[0])
                return
        else:
            forest.append((set([a]),set([b])))

    # グループ分け
    for x in data:
        if x[2] == 'yes':
            searchForestYes(*x[:-1])
        elif x[2] == 'no':
            searchForestNo(*x[:-1])

    return judge(forest, p1, p2)

def judge(forest, p1, p2):

    # 組み合わせを生成
    def comb(forest):
        if not forest:
            yield ()
            return

        for x in forest[0]:
            for y in comb(forest[1:]):
                yield tuple(x) + y

    def judge_(gen):
        cntDic = {x:len(x) for x in gen}
        p1_cnt = filter(lambda x:cntDic[x] == p1, cntDic)
        if len(p1_cnt) == 1:
            return sorted(p1_cnt[0]) + ['end']
        else:
            return ['no']

    gen = comb(forest)
    return judge_(gen)

def test():
    p1 , p2 = 4, 3
    data = [[1,2,'yes'],
            [1,3,'no'],
            [4,5,'yes'],
            [5,6,'yes'],
            [6,7,'no']]
    for x in solve(data, p1, p2):
        print(x)
if __name__=='__main__':
    # test()
    main()

Submission status: Accepted

Solution code:
from collections import defaultdict


class UnionFind():
    def __init__(self, n):
        self.parent = list(range(n))
        self.rank = [0] * n

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

    def unite(self, x, y):
        x, y = self.find(x), self.find(y)

        if x == y:
            return

        if self.rank[x] < self.rank[y]:
            self.parent[x] = y
        else:
            self.parent[y] = x
            if self.rank[x] == self.rank[y]:
                self.rank[x] += 1


while True:
    n, p1, p2 = (int(s) for s in input().split())
    if (n, p1, p2) == (0, 0, 0):
        break

    p = p1 + p2
    tree = UnionFind(p * 2)
    unions = defaultdict(list)

    for i in range(n):
        xs, ys, a = input().split()
        x, y = int(xs) - 1, int(ys) - 1
        if a == 'yes':
            tree.unite(x, y)
            tree.unite(x + p, y + p)
        else:
            tree.unite(x, y + p)
            tree.unite(x + p, y)

    for i in range(p):
        unions[tree.find(i)].append(i)
    roots = []
    sides = []
    diffs = []
    rest = p1
    for i in range(p):
        if i in unions:
            member_len, backside_len = len(unions[i]), len(unions[i + p])
            if member_len == backside_len:
                rest = -1
                break
            elif member_len < backside_len:
                diff = backside_len - member_len
                rest -= member_len
                sides.append(0)
            else:
                diff = member_len - backside_len
                sides.append(1)
                rest -= backside_len
            roots.append(i)
            diffs.append(diff)
    if rest < 0:
        print('no')
        continue

    dp = [[1] + [0] * rest for i in range(len(roots) + 1)]

    for i in reversed(range(len(roots))):
        for j in range(1, rest + 1):
            if j < diffs[i]:
                if dp[i + 1][j]:
                    dp[i][j] = 1
                else:
                    dp[i][j] = 0
            else:
                if dp[i + 1][j] and dp[i + 1][j - diffs[i]]:
                    dp[i][j] = 3
                elif dp[i + 1][j - diffs[i]]:
                    dp[i][j] = 2
                elif dp[i + 1][j]:
                    dp[i][j] = 1
                else:
                    dp[i][j] = 0

    divines = []
    for i in range(len(roots)):
        if dp[i][rest] == 1:
            divines.extend(unions[roots[i] + p * sides[i]])
        elif dp[i][rest] == 2:
            divines.extend(unions[roots[i] + p * (1 - sides[i])])
            rest -= diffs[i]
        else:
            print('no')
            break
    else:
        divines.sort()
        for divine in divines:
            print(divine + 1)
        print('end')

Submission status: Accepted

Solution code:
import sys
sys.setrecursionlimit(10000000)
MOD = 10 ** 9 + 7
INF = 10 ** 15

class UnionFind():
    def __init__(self,n):
        self.n = n
        self.parents = [-1]*n

    def find(self,x): #根を見つける、繋ぎ直す
        if self.parents[x] < 0:
            return x
        else:
            self.parents[x] = self.find(self.parents[x])
            return self.parents[x]
    
    def unite(self,x,y): #x,yの含むグループを併合する
        x = self.find(x)
        y = self.find(y)

        if x == y:
            return
        
        if self.parents[x] > self.parents[y]:
            x,y = y,x

        self.parents[x] += self.parents[y]
        self.parents[y] = x
    
    def same(self,x,y):#xとyが同じグループにいるか判定
        return self.find(x) == self.find(y)
    
    def members(self,x):#xと同じグループのメンバーを列挙
        root = self.find(x)
        return [i for i in range(self.n) if self.find(i) == root]
    
    def size(self,x):#xが属するグループのメンバーの数
        return -self.parents[self.find(x)]
    
    def roots(self):#ufの根を列挙
        return [i for i, x in enumerate(self.parents) if x < 0]

    def group_count(self):#グループの数を数える
        return len(self.roots())
    
    def all_group_members(self):#根:メンバの辞書を返す
        return {r: self.members(r) for r in self.roots()}

def solve(N,P,Q):
    M = P + Q
    uf = UnionFind(M + M)
    flag = True
    for _ in range(N):
        q = input().split()
        x = int(q[0]) - 1
        y = int(q[1]) - 1
        a = q[2]
        if a == 'yes':
            if x == y:
                continue
            if uf.same(x,y + M) or uf.same(x + M,y):
                flag = False
                break
            uf.unite(x,y)
            uf.unite(x + M,y + M)
        else:
            if x == y:
                flag = False
                break
            if uf.same(x,y) or uf.same(x + M,y + M):
                flag = False
                break
            uf.unite(x,y + M)
            uf.unite(x + M,y)
    
    if not flag:
        print('no')
        return
    for i in range(M):
        if uf.same(i,i + M):
            print('no')
            return
    
    root = uf.roots()
    member = uf.all_group_members()
    each_god = []
    before_searched = [0] * M
    candidate = []
    for r in root:
        god = 0
        evil = 0
        flag = True
        for m in member[r]:
            if m < M:
                if before_searched[m] == 1:
                    flag = False
                    break
                else:
                    god += 1
                    before_searched[m] = 1
            else:
                if before_searched[m - M] == 1:
                    flag = False
                    break
                else:
                    evil += 1
                    before_searched[m - M] = 1
        if flag:
            candidate.append(r)
            each_god.append((god,evil))

    dp = [[0]*(1 + P) for _ in range(len(candidate) + 1)]
    if each_god[0][0] <= P:
        dp[1][each_god[0][0]] = 1
    if each_god[0][1] <= P:
        dp[1][each_god[0][1]] += 1
    for i,(g,e) in enumerate(each_god[1:],1):
        for j in range(P + 1):
            if j - e >= 0:
                dp[i + 1][j] += dp[i][j - e]
            if j - g >= 0:
                dp[i + 1][j] += dp[i][j - g]
    
    #print('each_god: ',each_god)
    #print('candidate ',candidate)
    #print('dp: ',dp)
                
    if dp[-1][P] == 1:
        ans = []
        now = P
        for i in range(len(candidate) - 1,0,-1):
            if 0 <=  now - each_god[i][0] <= P and dp[i][now - each_god[i][0]] == 1:
                for m in member[candidate[i]]:
                    if m < M:
                        ans.append(m + 1)
                now -= each_god[i][0]
            elif 0 <= now - each_god[i][1] <= P and dp[i][now - each_god[i][1]] == 1:
                for m in member[candidate[i]]:
                    if m >= M:
                        ans.append(m - M + 1)
                now -= each_god[i][1]
        if now > 0:
            if now == each_god[0][0]:
                for m in member[candidate[0]]:
                    if m < M:
                        ans.append(m + 1)
            elif now == each_god[0][1]:
                for m in member[candidate[0]]:
                    if m >= M:
                        ans.append(m - M + 1)
        ans.sort()
        if ans:
            print('\n'.join(map(str,ans)))
        print('end')
    else:
        print('no')


def main():
    while True:
        N,P,Q = map(int,input().split())
        if N == 0 and P == 0 and Q == 0:
            return 
        solve(N,P,Q)
if __name__ == '__main__':
    main()