Problem:


Problem E: Cards

There are many blue cards and red cards on the table.
For each card, an integer number greater than 1 is printed on its face.
The same number may be printed on several cards.

A blue card and a red card can be paired when both of the numbers
printed on them have a common divisor greater than 1.
There may be more than one red card that can be paired with one blue card.
Also, there may be more than one blue card that can be paired with one red card.
When a blue card and a red card are chosen and paired,
these two cards are removed from the whole cards on the table.

Figure E-1: Four blue cards and three red cards

For example, in Figure E-1,
there are four blue cards and three red cards.
Numbers 2, 6, 6 and 15 are printed on the faces of the four blue cards, 
and 2, 3 and 35 are printed on those of the three red cards.
Here, you can make pairs of blue cards and red cards as follows.
First,
the blue card with number 2 on it and the red card with 2 are paired and removed.
Second,
one of the two blue cards with 6 and the red card with 3 are paired and removed.
Finally,
the blue card with 15 and the red card with 35 are paired and removed.
Thus the number of removed pairs is three.

Note that the total number of the pairs depends on
the way of choosing cards to be paired.
The blue card with 15 and the red card with 3 might be paired 
and removed at the beginning.
In this case, there are only one more pair that can be removed
and the total number of the removed pairs is two.

Your job is to find the largest number of pairs that can be removed from the given set of cards on the table.

Input

The input is a sequence of datasets.
The number of the datasets is less than or equal to 100.
Each dataset is formatted as follows.

m n 

b1 ... bk
... bm 

r1 ... rk
... rn 

The integers m and n are the number of blue cards
and that of red cards, respectively.
You may assume 1 ≤ m ≤ 500 and 1≤ n ≤ 500.

bk (1 ≤ k ≤ m) and
rk (1 ≤ k ≤ n) are
numbers printed on the blue cards and the red cards respectively,
that are integers greater than or equal to 2 and less than 
10000000 (=107). 
The input integers are separated by a space or a newline.
Each of bm and rn is
followed by a newline.
There are no other characters in the dataset.

The end of the input is indicated by a line containing two zeros
separated by a space.

Output

For each dataset, output a line containing an integer that indicates
the maximum of the number of the pairs. 

Sample Input

4 3
2 6 6 15
2 3 5
2 3
4 9
8 16 32
4 2
4 9 11 13
5 7
5 5
2 3 5 1001 1001
7 11 13 30 30
10 10
2 3 5 7 9 11 13 15 17 29
4 6 10 14 18 22 26 30 34 38
20 20
195 144 903 63 137 513 44 626 75 473
876 421 568 519 755 840 374 368 570 872
363 650 155 265 64 26 426 391 15 421
373 984 564 54 823 477 565 866 879 638
100 100
195 144 903 63 137 513 44 626 75 473
876 421 568 519 755 840 374 368 570 872
363 650 155 265 64 26 426 391 15 421
373 984 564 54 823 477 565 866 879 638
117 755 835 683 52 369 302 424 513 870
75 874 299 228 140 361 30 342 750 819
761 123 804 325 952 405 578 517 49 457
932 941 988 767 624 41 912 702 241 426
351 92 300 648 318 216 785 347 556 535
166 318 434 746 419 386 928 996 680 975
231 390 916 220 933 319 37 846 797 54
272 924 145 348 350 239 563 135 362 119
446 305 213 879 51 631 43 755 405 499
509 412 887 203 408 821 298 443 445 96
274 715 796 417 839 147 654 402 280 17
298 725 98 287 382 923 694 201 679 99
699 188 288 364 389 694 185 464 138 406
558 188 897 354 603 737 277 35 139 556
826 213 59 922 499 217 846 193 416 525
69 115 489 355 256 654 49 439 118 961
0 0

Output for the Sample Input

3
1
0
4
9
18
85



Sample input:
4 3
2 6 6 15
2 3 5
2 3
4 9
8 16 32
4 2
4 9 11 13
5 7
5 5
2 3 5 1001 1001
7 11 13 30 30
10 10
2 3 5 7 9 11 13 15 17 29
4 6 10 14 18 22 26 30 34 38
20 20
195 144 903 63 137 513 44 626 75 473
876 421 568 519 755 840 374 368 570 872
363 650 155 265 64 26 426 391 15 421
373 984 564 54 823 477 565 866 879 638
100 100
195 144 903 63 137 513 44 626 75 473
876 421 568 519 755 840 374 368 570 872
363 650 155 265 64 26 426 391 15 421
373 984 564 54 823 477 565 866 879 638
117 755 835 683 52 369 302 424 513 870
75 874 299 228 140 361 30 342 750 819
761 123 804 325 952 405 578 517 49 457
932 941 988 767 624 41 912 702 241 426
351 92 300 648 318 216 785 347 556 535
166 318 434 746 419 386 928 996 680 975
231 390 916 220 933 319 37 846 797 54
272 924 145 348 350 239 563 135 362 119
446 305 213 879 51 631 43 755 405 499
509 412 887 203 408 821 298 443 445 96
274 715 796 417 839 147 654 402 280 17
298 725 98 287 382 923 694 201 679 99
699 188 288 364 389 694 185 464 138 406
558 188 897 354 603 737 277 35 139 556
826 213 59 922 499 217 846 193 416 525
69 115 489 355 256 654 49 439 118 961
0 0


Sample output:
3
1
0
4
9
18
85

Submission status: Runtime Error

Solution code:
from collections import deque

inf = 100000000000000000

def bfs(graph, s, t):
    V = len(graph)
    q = deque([(s, -1, -1)])
    prev = [(-1, -1)] * V
    visited = [False] * V
    while len(q) > 0:
        (v, p, e) = q.popleft()
        if visited[v]:
            continue
        visited[v] = True
        prev[v] = p, e
        for i in range(len(graph[v])):
            e = graph[v][i]
            if e['cap'] > 0:
                q.append((e['to'], v, i))
    if not visited[t]:
        return None
    else:
        return prev

def decrease_graph(graph, s, t, prev):
    ((p, e), c) = prev[t], t
    m = inf
    while p != -1:
        m = min(graph[p][e]['cap'], m)
        ((p, e), c) = prev[p], p
    ((p, e), c) = prev[t], t
    while p != -1:
        graph[p][e]['cap'] -= m
        graph[c][graph[p][e]['rev']]['cap'] += m
        ((p, e), c) = prev[p], p
    return m

def maximum_flow(graph, s, t):
    V = len(graph)
h    g = [[] for _ in range(V)]
    for v in range(V):
        nei = graph[v]
        for (u, cap) in nei:
            g[v].append({'to' : u, 'from': v, 'cap': cap, 'rev': len(g[u])})
            g[u].append({'to' : v, 'from': u, 'cap':   0, 'rev': len(g[v]) - 1})
    
    sum = 0
    while True:
        prev = bfs(g, s, t)
        if prev == None:
            break
        sum += decrease_graph(g, s, t, prev)
    return sum

def gcd(x, y):
    while y > 0:
        x, y = y, x % y
    return x

def main():
    while True:
        m, n = map(int, input().split())
        if m == 0 and n == 0:
            return
        b = []
        while len(b) < m:
            b += list(map(int, input().split()))
        r = []
        while len(r) < n:
            r += list(map(int, input().split()))
        
        g = [[] for i in range(n + m + 2)]
        for i in range(m):
            g[0].append((i + 1, 1))
        for i in range(n):
            g[m + i + 1].append((n + m + 1, 1))
        for i in range(m):
            for j in range(n):
                if gcd(b[i], r[j]) > 1:
                    g[i + 1].append((m + j + 1, 1))

        print(maximum_flow(g, 0, n + m + 1))
        
main()

Submission status: Runtime Error

Solution code:
from collections import deque

inf = 100000000000000000

def bfs(graph, s, t):
    V = len(graph)
    q = deque([(s, -1, -1)])
    prev = [(-1, -1)] * V
    visited = [False] * V
    while len(q) > 0:
        (v, p, e) = q.popleft()
        if visited[v]:
            continue
        visited[v] = True
        prev[v] = p, e
        for i in range(len(graph[v])):
            e = graph[v][i]
            if e['cap'] > 0:
                q.append((e['to'], v, i))
    if not visited[t]:
        return None
    else:
        return prev

def decrease_graph(graph, s, t, prev):
    ((p, e), c) = prev[t], t
    m = inf
    while p != -1:
        m = min(graph[p][e]['cap'], m)
        ((p, e), c) = prev[p], p
    ((p, e), c) = prev[t], t
    while p != -1:
        graph[p][e]['cap'] -= m
        graph[c][graph[p][e]['rev']]['cap'] += m
        ((p, e), c) = prev[p], p
    return m

def maximum_flow(graph, s, t):
    V = len(graph)
h    g = [[] for _ in range(V)]
    for v in range(V):
        nei = graph[v]
        for (u, cap) in nei:
            g[v].append({'to' : u, 'from': v, 'cap': cap, 'rev': len(g[u])})
            g[u].append({'to' : v, 'from': u, 'cap':   0, 'rev': len(g[v]) - 1})
    
    sum = 0
    while True:
        prev = bfs(g, s, t)
        if prev == None:
            break
        sum += decrease_graph(g, s, t, prev)
    return sum

def gcd(x, y):
    while y > 0:
        x, y = y, x % y
    return x

def main():
    while True:
        m, n = map(int, input().split())
        if m == 0 and n == 0:
            return
        b = []
        b += list(map(int, input().split()))
        r = []
        r += list(map(int, input().split()))
        
        g = [[] for i in range(n + m + 2)]
        for i in range(m):
            g[0].append((i + 1, 1))
        for i in range(n):
            g[m + i + 1].append((n + m + 1, 1))
        for i in range(m):
            for j in range(n):
                if gcd(b[i], r[j]) > 1:
                    g[i + 1].append((m + j + 1, 1))

        print(maximum_flow(g, 0, n + m + 1))
        
main()

Submission status: Runtime Error

Solution code:
from collections import deque

inf = 100000000000000000

def bfs(graph, s, t):
    V = len(graph)
    q = deque([(s, -1, -1)])
    prev = [(-1, -1)] * V
    visited = [False] * V
    while len(q) > 0:
        (v, p, e) = q.popleft()
        if visited[v]:
            continue
        visited[v] = True
        prev[v] = p, e
        for i in range(len(graph[v])):
            e = graph[v][i]
            if e['cap'] > 0:
                q.append((e['to'], v, i))
    if not visited[t]:
        return None
    else:
        return prev

def decrease_graph(graph, s, t, prev):
    ((p, e), c) = prev[t], t
    m = inf
    while p != -1:
        m = min(graph[p][e]['cap'], m)
        ((p, e), c) = prev[p], p
    ((p, e), c) = prev[t], t
    while p != -1:
        graph[p][e]['cap'] -= m
        graph[c][graph[p][e]['rev']]['cap'] += m
        ((p, e), c) = prev[p], p
    return m

def maximum_flow(graph, s, t):
    V = len(graph)
    g = [[] for _ in range(V)]
    for v in range(V):
        nei = graph[v]
        for (u, cap) in nei:
            g[v].append({'to' : u, 'from': v, 'cap': cap, 'rev': len(g[u])})
            g[u].append({'to' : v, 'from': u, 'cap':   0, 'rev': len(g[v]) - 1})
    
    sum = 0
    while True:
        prev = bfs(g, s, t)
        if prev == None:
            break
        sum += decrease_graph(g, s, t, prev)
    return sum

def gcd(x, y):
    while y > 0:
        x, y = y, x % y
    return x

def main():
    while True:
        m, n = map(int, input().split())
        if m == 0 and n == 0:
            return
        b = []
        b += list(map(int, input().split()))
        r = []
        r += list(map(int, input().split()))
        
        g = [[] for i in range(n + m + 2)]
        for i in range(m):
            g[0].append((i + 1, 1))
        for i in range(n):
            g[m + i + 1].append((n + m + 1, 1))
        for i in range(m):
            for j in range(n):
                if gcd(b[i], r[j]) > 1:
                    g[i + 1].append((m + j + 1, 1))

        print(maximum_flow(g, 0, n + m + 1))
        
main()

Submission status: Runtime Error

Solution code:
from collections import deque

inf = 100000000000000000

def bfs(graph, s, t):
    V = len(graph)
    q = deque([(s, -1, -1)])
    prev = [(-1, -1)] * V
    visited = [False] * V
    while len(q) > 0:
        (v, p, e) = q.popleft()
        if visited[v]:
            continue
        visited[v] = True
        prev[v] = p, e
        for i in range(len(graph[v])):
            e = graph[v][i]
            if e['cap'] > 0:
                q.append((e['to'], v, i))
    if not visited[t]:
        return None
    else:
        return prev

def decrease_graph(graph, s, t, prev):
    ((p, e), c) = prev[t], t
    m = inf
    while p != -1:
        m = min(graph[p][e]['cap'], m)
        ((p, e), c) = prev[p], p
    ((p, e), c) = prev[t], t
    while p != -1:
        graph[p][e]['cap'] -= m
        graph[c][graph[p][e]['rev']]['cap'] += m
        ((p, e), c) = prev[p], p
    return m

def maximum_flow(graph, s, t):
    V = len(graph)
    g = [[] for _ in range(V)]
    for v in range(V):
        nei = graph[v]
        for (u, cap) in nei:
            g[v].append({'to' : u, 'from': v, 'cap': cap, 'rev': len(g[u])})
            g[u].append({'to' : v, 'from': u, 'cap':   0, 'rev': len(g[v]) - 1})
    
    sum = 0
    while True:
        prev = bfs(g, s, t)
        if prev == None:
            break
        sum += decrease_graph(g, s, t, prev)
    return sum

def gcd(x, y):
    while y > 0:
        x, y = y, x % y
    return x

def main():
    while True:
        m, n = map(int, input().split())
        if m == 0 and n == 0:
            return
        b = []
        while len(b) < m:
            b += list(map(int, input().split()))
        r = []
        while len(r) < n:
            r += list(map(int, input().split()))
        
        g = [[] for i in range(n + m + 2)]
        for i in range(m):
            g[0].append((i + 1, 1))
        for i in range(n):
            g[m + i + 1].append((n + m + 1, 1))
        for i in range(m):
            for j in range(n):
                if gcd(b[i], r[j]) > 1:
                    g[i + 1].append((m + j + 1, 1))

        print(maximum_flow(g, 0, n + m + 1))
        
main()

Submission status: Runtime Error

Solution code:
from collections import deque

inf = 100000000000000000

def bfs(graph, s, t):
    V = len(graph)
    q = deque([(s, -1, -1)])
    prev = [(-1, -1)] * V
    visited = [False] * V
    while len(q) > 0:
        (v, p, e) = q.popleft()
        if visited[v]:
            continue
        visited[v] = True
        prev[v] = p, e
        for i in range(len(graph[v])):
            e = graph[v][i]
            if e['cap'] > 0:
                q.append((e['to'], v, i))
    if not visited[t]:
        return None
    else:
        return prev

def decrease_graph(graph, s, t, prev):
    ((p, e), c) = prev[t], t
    m = inf
    while p != -1:
        m = min(graph[p][e]['cap'], m)
        ((p, e), c) = prev[p], p
    ((p, e), c) = prev[t], t
    while p != -1:
        graph[p][e]['cap'] -= m
        graph[c][graph[p][e]['rev']]['cap'] += m
        ((p, e), c) = prev[p], p
    return m

def maximum_flow(graph, s, t):
    V = len(graph)
    g = [[] for _ in range(V)]
    for v in range(V):
        nei = graph[v]
        for (u, cap) in nei:
            g[v].append({'to' : u, 'from': v, 'cap': cap, 'rev': len(g[u])})
            g[u].append({'to' : v, 'from': u, 'cap':   0, 'rev': len(g[v]) - 1})
    
    sum = 0
    while True:
        prev = bfs(g, s, t)
        if prev == None:
            break
        sum += decrease_graph(g, s, t, prev)
    return sum

def gcd(x, y):
    while y > 0:
        x, y = y, x % y
    return x

def main():
    while True:
        m, n = map(int, input().split())
        if m == 0 and n == 0:
            return
        data = []
        while len(data) < n + m:
            data += list(map(int, input().split()))
        b = data[:m]
        r = data[m:]
        while len(r) < n:
            r += list(map(int, input().split()))
        
        g = [[] for i in range(n + m + 2)]
        for i in range(m):
            g[0].append((i + 1, 1))
        for i in range(n):
            g[m + i + 1].append((n + m + 1, 1))
        for i in range(m):
            for j in range(n):
                if gcd(b[i], r[j]) > 1:
                    g[i + 1].append((m + j + 1, 1))

        print(maximum_flow(g, 0, n + m + 1))
        
main()

Submission status: Runtime Error

Solution code:
from collections import deque

inf = 100000000000000000

def dfs(graph, s, t):
    V = len(graph)
    prev = [(-1, -1)] * V
    visited = [False] * V
    visited[0] = True
    def iter(cur):
        if cur == t:
            return True
        for i in range(len(graph[cur])):
            e = graph[cur][i]
            if not visited[e['to']] and e['cap'] > 0 :
                prev[e['to']] = (cur, i)
                visited[e['to']] = True
                if iter(e['to']):
                    return True
        return False
        
    iter(s)
    if not visited[t]:
        return None
    else:
        return prev

def decrease_graph(graph, s, t, prev):
    ((p, e), c) = prev[t], t
    m = inf
    while p != -1:
        m = min(graph[p][e]['cap'], m)
        ((p, e), c) = prev[p], p
    ((p, e), c) = prev[t], t
    while p != -1:
        graph[p][e]['cap'] -= m
        graph[c][graph[p][e]['rev']]['cap'] += m
        ((p, e), c) = prev[p], p
    return m

def maximum_flow(graph, s, t):
    V = len(graph)
    g = [[] for _ in range(V)]
    for v in range(V):
        nei = graph[v]
        for (u, cap) in nei:
            g[v].append({'to' : u, 'from': v, 'cap': cap, 'rev': len(g[u])})
            g[u].append({'to' : v, 'from': u, 'cap':   0, 'rev': len(g[v]) - 1})
    
    sum = 0
    while True:
        prev = dfs(g, s, t)
        if prev == None:
            break
        sum += decrease_graph(g, s, t, prev)
    return sum

def gcd(x, y):
    while y > 0:
        x, y = y, x % y
    return x

def main():
    while True:
        m, n = map(int, input().split())
        if m == 0 and n == 0:
            return
        data = []
        while len(data) < n + m:
            data += list(map(int, input().split()))
        b = data[:m]
        r = data[m:]
        while len(r) < n:
            r += list(map(int, input().split()))
        
        g = [[] for i in range(n + m + 2)]
        for i in range(m):
            g[0].append((i + 1, 1))
        for i in range(n):
            g[m + i + 1].append((n + m + 1, 1))
        for i in range(m):
            for j in range(n):
                if gcd(b[i], r[j]) > 1:
                    g[i + 1].append((m + j + 1, 1))

        print(maximum_flow(g, 0, n + m + 1))
        
main()

Submission status: Runtime Error

Solution code:
from fractions import gcd


def add_edge(u, v):
    G[u].append(v)
    G[v].append(u)


def dfs(v):
    used[v] = True
    for u in G[v]:
        w = match[u]
        if w < 0 or not used[w] and dfs(w):
            match[v] = u
            match[u] = v
            return True
    else:
        return False


def bipartite_matching():
    result = 0
    match[:] = [-1] * (numv)
    for v in range(numv):
        if match[v] < 0:
            used[:] = [False] * numv
            if dfs(v):
                result += 1
    return result


while True:
    m, n = map(int, input().split())
    if (m, n) == (0, 0):
        break
    numv = m + n
    cards = []
    while len(cards) < numv:
        cards.extend(map(int, input().split()))
    blues = cards[:m]
    reds = cards[m:]
    G = [[] for i in range(numv)]
    used = [False] * numv
    match = [-1] * numv
    for i, b in enumerate(blues):
        for j, r in enumerate(reds, m):
            if gcd(b, r) > 1:
                add_edge(i, j)

    print(bipartite_matching())

Submission status: Runtime Error

Solution code:

from fractions import gcd


def add_edge(u, v):
    G[u].append(v)
    G[v].append(u)


def dfs(v):
    used[v] = True
    for u in G[v]:
        w = match[u]
        if w < 0 or not used[w] and dfs(w):
            match[v] = u
            match[u] = v
            return True
    else:
        return False


def bipartite_matching():
    result = 0
    match[:] = [-1] * (numv)
    for v in range(numv):
        if match[v] < 0:
            used[:] = [False] * numv
            if dfs(v):
                result += 1
    return result


while True:
    m, n = map(int, input().split())
    if (m, n) == (0, 0):
        break
    numv = m + n
    cards = []
    while len(cards) < numv:
        cards.extend(map(int, input().split()))
    blues = cards[:m]
    reds = cards[m:]
    G = [[] for i in range(numv)]
    used = [False] * numv
    match = [-1] * numv
    for i, b in enumerate(blues):
        for j, r in enumerate(reds, m):
            if gcd(b, r) > 1:
                add_edge(i, j)

    print(bipartite_matching())

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Cards
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1163&lang=jp

"""
import sys
from sys import stdin
from collections import namedtuple
from fractions import gcd
input = stdin.readline

edge = namedtuple('edge', ['to', 'cap', 'rev'])

def add_edge(G, f, t, c):
    G[f].append(edge(t, c, len(G[t])))
    G[t].append(edge(f, 0, len(G[f]) - 1))


def dfs(G, used, v, t, f):
    if v == t:
        return f
    used[v] = True
    for i in range(len(G[v])):
        e = G[v][i]
        if (not used[e.to]) and (e.cap > 0):
            d = dfs(G, used, e.to, t, min(f, e.cap))
            if d > 0:
                G[v][i] = edge(e.to, e.cap - d, e.rev)
                G[e.to][e.rev] = edge(G[e.to][e.rev].to, G[e.to][e.rev].cap + d, G[e.to][e.rev].rev)
                return d
    return 0


def max_flow(G, V,s, t):
    used = [False] * V
    flow = 0
    while True:
        for i in range(len(used)):
            used[i] = False
        f = dfs(G, used, s, t, float('inf'))
        if f == 0:
            return flow
        flow += f


def main(args):
    """
    0: ソース
    1〜m: 青
    m+1〜m+n: 赤
    m+n+1: シンク
    """
    while True:
        m, n = map(int, input().split())
        if m == 0 and n == 0:
            break

        blue_cards = []
        red_cards = []
        while True:
            blue_cards.extend([int(b) for b in input().split()])
            if len(blue_cards) == m:
                break
        while True:
            red_cards.extend([int(r) for r in input().split()])
            if len(red_cards) == n:
                break

        G = [[] for _ in range(m+n+2)]

        for b in range(1, m+1):
            add_edge(G, 0, b, 1)
        for r in range(m+1, m+n+1):
            add_edge(G, r, m+n+1, 1)

        for bi, b in enumerate(blue_cards, start=1):
            for ri, r in enumerate(red_cards, start=m+1):
                if gcd(b, r) != 1:
                    add_edge(G, bi, ri, 1)

        ans = max_flow(G, m+n+2, 0, m+n+1)
        print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Cards
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1163&lang=jp

"""
import sys
from sys import stdin
from collections import namedtuple
from math import gcd
input = stdin.readline

edge = namedtuple('edge', ['to', 'cap', 'rev'])

def add_edge(G, f, t, c):
    G[f].append(edge(t, c, len(G[t])))
    G[t].append(edge(f, 0, len(G[f]) - 1))


def dfs(G, used, v, t, f):
    if v == t:
        return f
    used[v] = True
    for i in range(len(G[v])):
        e = G[v][i]
        if (not used[e.to]) and (e.cap > 0):
            d = dfs(G, used, e.to, t, min(f, e.cap))
            if d > 0:
                G[v][i] = edge(e.to, e.cap - d, e.rev)
                G[e.to][e.rev] = edge(G[e.to][e.rev].to, G[e.to][e.rev].cap + d, G[e.to][e.rev].rev)
                return d
    return 0


def max_flow(G, V,s, t):
    used = [False] * V
    flow = 0
    while True:
        for i in range(len(used)):
            used[i] = False
        f = dfs(G, used, s, t, float('inf'))
        if f == 0:
            return flow
        flow += f


def main(args):
    """
    0: ソース
    1〜m: 青
    m+1〜m+n: 赤
    m+n+1: シンク
    """
    while True:
        m, n = map(int, input().split())
        if m == 0 and n == 0:
            break

        blue_cards = []
        red_cards = []
        while True:
            blue_cards.extend([int(b) for b in input().split()])
            if len(blue_cards) == m:
                break
        while True:
            red_cards.extend([int(r) for r in input().split()])
            if len(red_cards) == n:
                break

        G = [[] for _ in range(m+n+2)]

        for b in range(1, m+1):
            add_edge(G, 0, b, 1)
        for r in range(m+1, m+n+1):
            add_edge(G, r, m+n+1, 1)

        for bi, b in enumerate(blue_cards, start=1):
            for ri, r in enumerate(red_cards, start=m+1):
                if gcd(b, r) != 1:
                    add_edge(G, bi, ri, 1)

        ans = max_flow(G, m+n+2, 0, m+n+1)
        print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Runtime Error

Solution code:
# -*- coding: utf-8 -*-
"""
Cards
http://judge.u-aizu.ac.jp/onlinejudge/description.jsp?id=1163&lang=jp

"""
import sys
from sys import stdin
from collections import namedtuple, deque
from math import gcd
input = stdin.readline

edge = namedtuple('edge', ['to', 'cap', 'rev'])


def add_edge(G, f, t, c):
    G[f].append(edge(t, c, len(G[t])))
    G[t].append(edge(f, 0, len(G[f]) - 1))


def bfs(G, level, s):
    for i in range(len(level)):
        level[i] = -1
    que = deque()
    level[s] = 0
    que.append(s)
    while que:
        v = que.popleft()
        for e in G[v]:
            if e.cap > 0 and level[e.to] < 0:
                level[e.to] = level[v] + 1
                que.append(e.to)


def dfs(G, iter, level, v, t, f):
    if v == t:
        return f
    for i in range(iter[v], len(G[v])):
        e = G[v][i]
        if e.cap > 0 and level[v] < level[e.to]:
            d = dfs(G, iter, level, e.to, t, min(f, e.cap))
            if d > 0:
                G[v][i] = edge(e.to, e.cap - d, e.rev)
                G[e.to][e.rev] = edge(G[e.to][e.rev].to, G[e.to][e.rev].cap + d, G[e.to][e.rev].rev)
                return d
    return 0

def max_flow(G, V, s, t):
    level = [0] * V
    flow = 0
    while True:
        bfs(G, level, s)
        if level[t] < 0:
            return flow
        iter = [0] * V
        while True:
            f = dfs(G, iter, level, s, t, float('inf'))
            if f > 0:
                flow += f
            else:
                break


def main(args):
    """
    0: ソース
    1〜m: 青
    m+1〜m+n: 赤
    m+n+1: シンク
    """
    while True:
        m, n = map(int, input().split())
        if m == 0 and n == 0:
            break

        blue_cards = []
        red_cards = []
        while True:
            blue_cards.extend([int(b) for b in input().split()])
            if len(blue_cards) == m:
                break
        while True:
            red_cards.extend([int(r) for r in input().split()])
            if len(red_cards) == n:
                break

        G = [[] for _ in range(m+n+2)]

        for b in range(1, m+1):
            add_edge(G, 0, b, 1)
        for r in range(m+1, m+n+1):
            add_edge(G, r, m+n+1, 1)

        for bi, b in enumerate(blue_cards, start=1):
            for ri, r in enumerate(red_cards, start=m+1):
                if gcd(b, r) != 1:
                    add_edge(G, bi, ri, 1)

        ans = max_flow(G, m+n+2, 0, m+n+1)
        print(ans)


if __name__ == '__main__':
    main(sys.argv[1:])

Submission status: Runtime Error

Solution code:
from collections import defaultdict
from fractions import gcd

INF = 2 << 30
MAX_V = 1002
G = [[] for _ in xrange(MAX_V)]
visited = [False]*MAX_V

def add_edge(fro, to, cap):
    G[fro].append([to,cap,len(G[to])])
    G[to].append([fro,0,len(G[fro])-1])

def dfs(v,t,f):
    global visited
    if v == t:
        return f
    visited[v] = True
    for i,(to,cap,rev) in enumerate((G[v])):
        if visited[to] or cap == 0:            
            continue        
        d = dfs(to,t,min(f,cap))
        if d > 0:
            G[v][i][1] -= d
            G[to][rev][1] += d
            return d
    return 0

def max_flow(s,t):
    global visited
    flow = 0
    while True:
        visited = [False]*MAX_V
        f = dfs(s,t,INF)
        if f == 0:
            return flow
        flow += f

while True:
    m,n = map(int,raw_input().split())
    if m|n == 0:
        break
    G = [[] for _ in xrange(MAX_V)]
    data = []
    while len(data) < n+m:
        data += map(int,raw_input().split())    
    blue = data[:m]
    red = data[m:]
    for i,b in enumerate(blue):
        add_edge(MAX_V-2,i,1)
    for i,r in enumerate(red):
        add_edge(i+m,MAX_V-1,1)
    for i in xrange(m):
        for j in xrange(n):
            if gcd(blue[i],red[j]) != 1:
                add_edge(i,j+m,1)
    print max_flow(MAX_V-2,MAX_V-1)

Submission status: Runtime Error

Solution code:
from collections import defaultdict
from fractions import gcd

INF = 2 << 30
MAX_V = 1003
G = [[] for _ in xrange(MAX_V)]
visited = [False]*MAX_V

def add_edge(fro, to, cap):
    G[fro].append([to,cap,len(G[to])])
    G[to].append([fro,0,len(G[fro])-1])

def dfs(v,t,f):
    global visited
    if v == t:
        return f
    visited[v] = True
    for i,(to,cap,rev) in enumerate((G[v])):
        if visited[to] or cap == 0:            
            continue        
        d = dfs(to,t,min(f,cap))
        if d > 0:
            G[v][i][1] -= d
            G[to][rev][1] += d
            return d
    return 0

def max_flow(s,t):
    global visited
    flow = 0
    while True:
        visited = [False]*MAX_V
        f = dfs(s,t,INF)
        if f == 0:
            return flow
        flow += f

while True:
    m,n = map(int,raw_input().split())
    if m|n == 0:
        break
    G = [[] for _ in xrange(MAX_V)]
    data = []
    while len(data) < n+m:
        data += map(int,raw_input().split())    
    blue = data[:m]
    red = data[m:]
    for i,b in enumerate(blue):
        add_edge(MAX_V-2,i,1)
    for i,r in enumerate(red):
        add_edge(i+m,MAX_V-1,1)
    for i in xrange(m):
        for j in xrange(n):
            if gcd(blue[i],red[j]) != 1:
                add_edge(i,j+m,1)
    print max_flow(MAX_V-2,MAX_V-1)

Submission status: Runtime Error

Solution code:
from fractions import gcd

INF = 2 << 30
V = 1003
G = [[] for _ in xrange(V)]
visited = [False]*V

def add_edge(fro, to, cap):
    G[fro].append([to,cap,len(G[to])])
    G[to].append([fro,0,len(G[fro])-1])

def dfs(v,t,f):
    if v == t:
        return f
    visited[v] = True
    for i,(to,cap,rev) in enumerate((G[v])):
        if visited[to] or cap <= 0:            
            continue        
        d = dfs(to,t,min(f,cap))
        if d > 0:
            G[v][i][1] -= d
            G[to][rev][1] += d
            return d
    return 0

def max_flow(s,t):
    flow = 0
    while True:
        for i in xrange(V):
            visited[i] = False
        f = dfs(s,t,INF)
        if f == 0:
            return flow
        flow += f

while True:
    m,n = map(int,raw_input().split())
    if m|n == 0:
        break
    V = m+n+2
    G = [[] for _ in xrange(V)]
    data = []
    while len(data) < n+m:
        data += map(int,raw_input().split())            
    blue = data[:m]
    red = data[m:]
    for i,b in enumerate(blue):
        add_edge(V-2,i,1)
    for i,r in enumerate(red):
        add_edge(i+m,V-1,1)
    for i in xrange(m):
        for j in xrange(n):
            if gcd(blue[i],red[j]) != 1:
                add_edge(i,j+m,1)
    print max_flow(V-2,V-1)