Problem:


Problem D: Luigi's Tavern

Luigi's Tavern is a thriving tavern in the Kingdom of Nahaila. The owner of the tavern Luigi supports to
organize a party, because the main customers of the tavern are adventurers. Each adventurer has a job:
hero, warrior, cleric or mage.

Any party should meet the following conditions:

    
 A party should have a hero.

    
 The warrior and the hero in a party should get along with each other.

    
 The cleric and the warrior in a party should get along with each other.

    
 The mage and the cleric in a party should get along with each other.

    
 It is recommended that a party has a warrior, a cleric, and a mage, but it is allowed that at most
      NW, NC and Nm parties does not have a warrior, a cleric, and a mage respectively.

    
 A party without a cleric should have a warrior and a mage.

Now, the tavern has H heroes, W warriors, C clerics and M mages. Your job is to write a program to find the maximum number of parties they can form.

Input

The input consists of multiple datasets. Each dataset has the following format:

The first line of the input contains 7 non-negative integers H, W, C, M, NW, NC, and NM, each of which is less than or equals to 50. The i-th of the following W lines contains the list of heroes who will be getting along with the warrior i. The list begins with a non-negative integer ni , less than or equals to H. Then the rest of the line should contain ni positive integers, each of which indicates the ID of a hero getting along with the warrior i.

After these lists, the following C lines contain the lists of warriors getting along with the clerics in the same manner. The j-th line contains a list of warriors who will be getting along with the cleric j. Then the last M lines of the input contain the lists of clerics getting along with the mages, of course in the same
manner. The k-th line contains a list of clerics who will be getting along with the mage k.

The last dataset is followed by a line containing seven negative integers. This line is not a part of any dataset and should not be processed.

Output

For each dataset, you should output the maximum number of parties possible.

Sample Input

2 1 1 1 1 1 1
1 1
1 1
1 1
1 1 1 1 0 0 0
1 1
1 1
1 1
1 0 1 0 1 0 1
0
1 1 0 1 0 1 0
0
0
1 1 0 1 0 1 0
1 1
0
-1 -1 -1 -1 -1 -1 -1

Output for the Sample Input

2
1
1
0
1



Sample input:
2 1 1 1 1 1 1
1 1
1 1
1 1
1 1 1 1 0 0 0
1 1
1 1
1 1
1 0 1 0 1 0 1
0
1 1 0 1 0 1 0
0
0
1 1 0 1 0 1 0
1 1
0
-1 -1 -1 -1 -1 -1 -1


Sample output:
2
1
1
0
1

Submission status: Wrong Answer

Solution code:
import collections


class MaxFlow:
    """Dinic Algorithm: find max-flow
       complexity: O(EV^2)
       used in GRL6A(AOJ)
    """
    class Edge:
        def __init__(self, to, cap, rev):
            self.to, self.cap, self.rev = to, cap, rev

    def __init__(self, V):
        """ V: the number of vertexes
            E: adjacency list
            source: start point
            sink: goal point
        """
        self.V = V
        self.E = [[] for _ in range(V)]

    def add_edge(self, fr, to, cap):
        self.E[fr].append(self.Edge(to, cap, len(self.E[to])))
        self.E[to].append(self.Edge(fr, 0, len(self.E[fr])-1))

    def run(self, source, sink, INF=10**9):
        """find max-flow"""
        maxflow = 0
        while True:
            self.bfs(source)
            if self.level[sink] < 0:
                return maxflow
            self.itr = [0] * self.V
            while True:
                flow = self.dfs(source, sink, INF)
                if flow > 0:
                    maxflow += flow
                else:
                    break

    def dfs(self, vertex, sink, flow):
        """find augmenting path"""
        if vertex == sink:
            return flow
        for i in range(self.itr[vertex], len(self.E[vertex])):
            self.itr[vertex] = i
            e = self.E[vertex][i]
            if e.cap > 0 and self.level[vertex] < self.level[e.to]:
                d = self.dfs(e.to, sink, min(flow, e.cap))
                if d > 0:
                    e.cap -= d
                    self.E[e.to][e.rev].cap += d
                    return d
        return 0

    def bfs(self, start):
        """find shortest path from start"""
        que = collections.deque()
        self.level = [-1] * self.V
        que.append(start)
        self.level[start] = 0

        while que:
            fr = que.popleft()
            for e in self.E[fr]:
                if e.cap > 0 and self.level[e.to] < 0:
                    self.level[e.to] = self.level[fr] + 1
                    que.append(e.to)

while True:
    row = list(map(int, input().split()))
    H, W, C, M, NW, NC, NM = row
    if H == -1:
        break
    mf = MaxFlow(sum(row) + 2)
    source = sum(row)
    sink = source + 1

    toH = lambda i: i
    toW = lambda i: sum(row[:1]) + i
    toC = lambda i: sum(row[:2]) + i
    toM = lambda i: sum(row[:3]) + i
    toNW = lambda i: sum(row[:4]) + i
    toNC = lambda i: sum(row[:5]) + i
    toNM = lambda i: sum(row[:6]) + i

    for i in range(H):
        mf.add_edge(source, toH(i), 1)
        for j in range(NW):
            mf.add_edge(toH(i), toNW(j), 1)

    for i in range(W):
        _, *friends = map(lambda x: int(x) - 1, input().split())
        for friend in friends:
            mf.add_edge(toH(friend), toW(i), 1)
        for j in range(NC):
            mf.add_edge(toW(i), toNC(j), 1)

    for i in range(C):
        _, *friends = map(lambda x: int(x) - 1, input().split())
        for friend in friends:
            mf.add_edge(toW(friend), toC(i), 1)
        for j in range(NW):
            mf.add_edge(toNW(j), toC(i), 1)
        for j in range(NM):
            mf.add_edge(toC(i), toNM(j), 1)

    for i in range(M):
        _, *friends = map(lambda x: int(x) - 1, input().split())
        for friend in friends:
            mf.add_edge(toC(friend), toM(i), 1)
        for j in range(NC):
            mf.add_edge(toNC(j), toM(i), 1)
        mf.add_edge(toM(i), sink, 1)

    for i in range(NM):
        mf.add_edge(toNC(i), sink, 1)

    print(mf.run(source, sink))

Submission status: Accepted

Solution code:
import collections


class MaxFlow:
    """Dinic Algorithm: find max-flow
       complexity: O(EV^2)
       used in GRL6A(AOJ)
    """
    class Edge:
        def __init__(self, to, cap, rev):
            self.to, self.cap, self.rev = to, cap, rev

    def __init__(self, V):
        """ V: the number of vertexes
            E: adjacency list
            source: start point
            sink: goal point
        """
        self.V = V
        self.E = [[] for _ in range(V)]

    def add_edge(self, fr, to, cap):
        self.E[fr].append(self.Edge(to, cap, len(self.E[to])))
        self.E[to].append(self.Edge(fr, 0, len(self.E[fr])-1))

    def run(self, source, sink, INF=10**9):
        """find max-flow"""
        maxflow = 0
        while True:
            self.bfs(source)
            if self.level[sink] < 0:
                return maxflow
            self.itr = [0] * self.V
            while True:
                flow = self.dfs(source, sink, INF)
                if flow > 0:
                    maxflow += flow
                else:
                    break

    def dfs(self, vertex, sink, flow):
        """find augmenting path"""
        if vertex == sink:
            return flow
        for i in range(self.itr[vertex], len(self.E[vertex])):
            self.itr[vertex] = i
            e = self.E[vertex][i]
            if e.cap > 0 and self.level[vertex] < self.level[e.to]:
                d = self.dfs(e.to, sink, min(flow, e.cap))
                if d > 0:
                    e.cap -= d
                    self.E[e.to][e.rev].cap += d
                    return d
        return 0

    def bfs(self, start):
        """find shortest path from start"""
        que = collections.deque()
        self.level = [-1] * self.V
        que.append(start)
        self.level[start] = 0

        while que:
            fr = que.popleft()
            for e in self.E[fr]:
                if e.cap > 0 and self.level[e.to] < 0:
                    self.level[e.to] = self.level[fr] + 1
                    que.append(e.to)

while True:
    H, W, C, M, NW, NC, NM = map(int, input().split())
    if H == -1:
        break
    V = H + 2 * (W + C) + M + 5 + 2
    mf = MaxFlow(V)
    source, sink = V - 2, V - 1

    inH = lambda i: i
    inW = lambda i: H + i
    outW = lambda i: H + W + i
    inC = lambda i: H + 2 * W + i
    outC = lambda i: H + 2 * W + C + i
    inM = lambda i: H + 2 * (W + C) + i
    inNW = H + 2 * (W + C) + M
    outNW = inNW + 1
    inNC = outNW + 1
    outNC = inNC + 1
    inNM = outNC + 1

    # source -> H
    for i in range(H):
        mf.add_edge(source, inH(i), 1)

    # H -> inW
    for i in range(W):
        friends = [int(x) - 1 for x in input().split()][1:]
        for friend in friends:
            mf.add_edge(inH(friend), inW(i), 1)

    # H -> inNW
    for i in range(H):
        mf.add_edge(inH(i), inNW, 1)

    # inW -> outW, inNW -> outNW
    for i in range(W):
        mf.add_edge(inW(i), outW(i), 1)
    mf.add_edge(inNW, outNW, NW)

    # outW -> inC, outNW -> inC
    for i in range(C):
        friends = [int(x) - 1 for x in input().split()][1:]
        for friend in friends:
            mf.add_edge(outW(friend), inC(i), 1)
        mf.add_edge(outNW, inC(i), 1)

    # outW -> inNC
    for i in range(W):
        mf.add_edge(outW(i), inNC, 1)

    # inC -> outC, inNC -> outNC
    for i in range(C):
        mf.add_edge(inC(i), outC(i), 1)
    mf.add_edge(inNC, outNC, NC)

    # outC -> M, outNC -> M
    for i in range(M):
        friends = [int(x) - 1 for x in input().split()][1:]
        for friend in friends:
            mf.add_edge(outC(friend), inM(i), 1)
        mf.add_edge(outNC, inM(i), 1)

    # outC -> NM
    for i in range(C):
        mf.add_edge(outC(i), inNM, 1)

    # M -> sink, NM -> sink
    for i in range(M):
        mf.add_edge(inM(i), sink, 1)
    mf.add_edge(inNM, sink, NM)

    print(mf.run(source, sink))

Submission status: Accepted

Solution code:
import collections
import sys
if sys.version[0] == '2':
    range, input = xrange, raw_input


class MaxFlow:
    """Dinic Algorithm: find max-flow
       complexity: O(EV^2)
       used in GRL6A(AOJ)
    """
    class Edge:
        def __init__(self, to, cap, rev):
            self.to, self.cap, self.rev = to, cap, rev

    def __init__(self, V):
        """ V: the number of vertexes
            E: adjacency list
            source: start point
            sink: goal point
        """
        self.V = V
        self.E = [[] for _ in range(V)]

    def add_edge(self, fr, to, cap):
        self.E[fr].append(self.Edge(to, cap, len(self.E[to])))
        self.E[to].append(self.Edge(fr, 0, len(self.E[fr])-1))

    def run(self, source, sink, INF=10**9):
        """find max-flow"""
        maxflow = 0
        while True:
            self.bfs(source)
            if self.level[sink] < 0:
                return maxflow
            self.itr = [0] * self.V
            while True:
                flow = self.dfs(source, sink, INF)
                if flow > 0:
                    maxflow += flow
                else:
                    break

    def dfs(self, vertex, sink, flow):
        """find augmenting path"""
        if vertex == sink:
            return flow
        for i in range(self.itr[vertex], len(self.E[vertex])):
            self.itr[vertex] = i
            e = self.E[vertex][i]
            if e.cap > 0 and self.level[vertex] < self.level[e.to]:
                d = self.dfs(e.to, sink, min(flow, e.cap))
                if d > 0:
                    e.cap -= d
                    self.E[e.to][e.rev].cap += d
                    return d
        return 0

    def bfs(self, start):
        """find shortest path from start"""
        que = collections.deque()
        self.level = [-1] * self.V
        que.append(start)
        self.level[start] = 0

        while que:
            fr = que.popleft()
            for e in self.E[fr]:
                if e.cap > 0 and self.level[e.to] < 0:
                    self.level[e.to] = self.level[fr] + 1
                    que.append(e.to)

while True:
    H, W, C, M, NW, NC, NM = map(int, input().split())
    if H == -1:
        break
    V = H + 2 * (W + C) + M + 5 + 2
    mf = MaxFlow(V)
    source, sink = V - 2, V - 1

    inH = lambda i: i
    inW = lambda i: H + i
    outW = lambda i: H + W + i
    inC = lambda i: H + 2 * W + i
    outC = lambda i: H + 2 * W + C + i
    inM = lambda i: H + 2 * (W + C) + i
    inNW = H + 2 * (W + C) + M
    outNW = inNW + 1
    inNC = outNW + 1
    outNC = inNC + 1
    inNM = outNC + 1

    # source -> H
    for i in range(H):
        mf.add_edge(source, inH(i), 1)

    # H -> inW
    for i in range(W):
        friends = [int(x) - 1 for x in input().split()][1:]
        for friend in friends:
            mf.add_edge(inH(friend), inW(i), 1)

    # H -> inNW
    for i in range(H):
        mf.add_edge(inH(i), inNW, 1)

    # inW -> outW, inNW -> outNW
    for i in range(W):
        mf.add_edge(inW(i), outW(i), 1)
    mf.add_edge(inNW, outNW, NW)

    # outW -> inC, outNW -> inC
    for i in range(C):
        friends = [int(x) - 1 for x in input().split()][1:]
        for friend in friends:
            mf.add_edge(outW(friend), inC(i), 1)
        mf.add_edge(outNW, inC(i), 1)

    # outW -> inNC
    for i in range(W):
        mf.add_edge(outW(i), inNC, 1)

    # inC -> outC, inNC -> outNC
    for i in range(C):
        mf.add_edge(inC(i), outC(i), 1)
    mf.add_edge(inNC, outNC, NC)

    # outC -> M, outNC -> M
    for i in range(M):
        friends = [int(x) - 1 for x in input().split()][1:]
        for friend in friends:
            mf.add_edge(outC(friend), inM(i), 1)
        mf.add_edge(outNC, inM(i), 1)

    # outC -> NM
    for i in range(C):
        mf.add_edge(outC(i), inNM, 1)

    # M -> sink, NM -> sink
    for i in range(M):
        mf.add_edge(inM(i), sink, 1)
    mf.add_edge(inNM, sink, NM)

    print(mf.run(source, sink))

Submission status: Accepted

Solution code:
import sys
readline = sys.stdin.readline
write = sys.stdout.write

from collections import deque
class PushRelabel:
    def __init__(self, N):
        self.N = N
        self.G = [[] for i in range(N)]
        self.initial = [N]*N
        self.zeros = [0]*N

    def add_edge(self, fr, to, cap):
        forward = [to, cap, None]
        forward[2] = backward = [fr, 0, forward]
        self.G[fr].append(forward)
        self.G[to].append(backward)

    def add_multi_edge(self, v1, v2, cap1, cap2):
        edge1 = [v2, cap1, None]
        edge1[2] = edge2 = [v1, cap2, edge1]
        self.G[v1].append(edge1)
        self.G[v2].append(edge2)

    def bfs(self, H, D, active, t, que=deque()):
        N = self.N
        B = [[] for i in range(N)]
        que.append(t)
        G = self.G
        H[:] = self.initial
        H[t] = 0
        D[:] = self.zeros
        D[0] = 1
        cur = 0
        while que:
            v = que.popleft()
            d = H[v] + 1
            for w, cap, backward in G[v]:
                if H[w] <= d or backward[1] == 0:
                    continue
                H[w] = d
                if active[w] and d < N:
                    B[d].append(w)
                    cur = d
                if d < N:
                    D[d] += 1
                que.append(w)
        return B, cur, d

    def flow(self, s, t):
        N = self.N
        H = [0]*N
        F = [0]*N
        D = [0]*(N+1)
        active = [0]*N

        G = self.G

        F[s] = 10**18
        active[s] = 1

        B, cur, gap = self.bfs(H, D, active, t)
        B[cur].append(s)

        cnt = 0
        while 1:
            while cur >= 0 and not B[cur]:
                cur -= 1
            if cur < 0:
                break
            v = B[cur].pop()
            if v == t:
                continue

            hv = H[v]
            if hv > gap:
                if hv < N:
                    D[hv] -= 1
                hv = H[v] = N
                continue
            rest = F[v]
            for e in G[v]:
                w, cap, backward = e
                if cap and hv > H[w] < gap:
                    d = min(rest, cap)
                    e[1] -= d
                    backward[1] += d
                    rest -= d
                    F[w] += d
                    if not active[w]:
                        hw = H[w]
                        B[hw].append(w)
                        if cur < hw:
                            cur = hw
                        active[w] = 1
                    if rest == 0:
                        break
            F[v] = rest

            if rest == 0:
                active[v] = 0
                continue

            h0 = H[v]
            hv = N
            for w, cap, backward in G[v]:
                if cap and hv > H[w] + 1 <= gap:
                    hv = H[w] + 1
            if h0 != hv:
                D[h0] -= 1
                if D[h0] == 0 and h0 < gap:
                    gap = h0
                    hv = N
                elif hv == gap:
                    gap += 1
                if hv < N:
                    D[hv] += 1

            H[v] = hv
            if hv < N:
                B[hv].append(v)
                if cur < hv:
                    cur = hv
            else:
                active[v] = 0

            cnt += 1
            if cnt % N == 0:
                B, cur, gap = self.bfs(H, D, active, t)
        return F[t]

def solve():
    H, W, C, M, NW, NC, NM = map(int, readline().split())
    if H == -1:
        return False
    pr = PushRelabel(2 + H + 2*(W + NW) + 2*(C + NC) + (M + NM))
    a0 = 2
    b0 = 2+H
    b1 = 2+H+(W+NW)
    c0 = 2+H+2*(W+NW)
    c1 = 2+H+2*(W+NW)+(C+NC)
    d0 = 2+H+2*(W+NW)+2*(C+NC)
    for i in range(H):
        pr.add_edge(0, a0+i, 1)

    for i in range(W):
        k, *ws = map(int, readline().split())
        for w in ws:
            pr.add_edge(a0+w-1, b0+i, 1)
        pr.add_edge(b0+i, b1+i, 1)
    for i in range(W, W+NW):
        for j in range(H):
            pr.add_edge(a0+j, b0+i, 1)
        for j in range(C):
            pr.add_edge(b1+i, c0+j, 1)
        pr.add_edge(b0+i, b1+i, 1)

    for i in range(C):
        k, *cs = map(int, readline().split())
        for c in cs:
            pr.add_edge(b1+c-1, c0+i, 1)
        pr.add_edge(c0+i, c1+i, 1)
    for i in range(C, C+NC):
        for j in range(W):
            pr.add_edge(b1+j, c0+i, 1)
        for j in range(M):
            pr.add_edge(c1+i, d0+j, 1)
        pr.add_edge(c0+i, c1+i, 1)

    for i in range(M):
        k, *ms = map(int, readline().split())
        for m in ms:
            pr.add_edge(c1+m-1, d0+i, 1)
        pr.add_edge(d0+i, 1, 1)
    for i in range(M, M+NM):
        for j in range(C):
            pr.add_edge(c1+j, d0+i, 1)
        pr.add_edge(d0+i, 1, 1)

    write("%d\n" % pr.flow(0, 1))
    return True
while solve():
    ...