Problem:


Score : 1200 points

Problem Statement

There are 2N balls in the xy-plane. The coordinates of the i-th of them is (x_i, y_i).
Here, x_i and y_i are integers between 1 and N (inclusive) for all i, and no two balls occupy the same coordinates.

In order to collect these balls, Snuke prepared 2N robots, N of type A and N of type B.
Then, he placed the type-A robots at coordinates (1, 0), (2, 0), ..., (N, 0), and the type-B robots at coordinates (0, 1), (0, 2), ..., (0, N), one at each position.

When activated, each type of robot will operate as follows.

When a type-A robot is activated at coordinates (a, 0), it will move to the position of the ball with the lowest y-coordinate among the balls on the line x = a, collect the ball and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.

When a type-B robot is activated at coordinates (0, b), it will move to the position of the ball with the lowest x-coordinate among the balls on the line y = b, collect the ball and deactivate itself. If there is no such ball, it will just deactivate itself without doing anything.

Once deactivated, a robot cannot be activated again. Also, while a robot is operating, no new robot can be activated until the operating robot is deactivated.

When Snuke was about to activate a robot, he noticed that he may fail to collect all the balls, depending on the order of activating the robots.

Among the (2N)! possible orders of activating the robots, find the number of the ones such that all the balls can be collected, modulo 1 000 000 007.

Constraints

2 \leq N \leq 10^5

1 \leq x_i \leq N

1 \leq y_i \leq N

If i ≠ j, either x_i ≠ x_j or y_i ≠ y_j.

Inputs

Input is given from Standard Input in the following format:

N
x_1 y_1
...
x_{2N} y_{2N}

Outputs

Print the number of the orders of activating the robots such that all the balls can be collected, modulo 1 000 000 007.

Sample Input 1

2
1 1
1 2
2 1
2 2

Sample Output 1

8

We will refer to the robots placed at (1, 0) and (2, 0) as A1 and A2, respectively, and the robots placed at (0, 1) and (0, 2) as B1 and B2, respectively.
There are eight orders of activation that satisfy the condition, as follows:

A1, B1, A2, B2

A1, B1, B2, A2

A1, B2, B1, A2

A2, B1, A1, B2

B1, A1, B2, A2

B1, A1, A2, B2

B1, A2, A1, B2

B2, A1, B1, A2

Thus, the output should be 8.

Sample Input 2

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

Sample Output 2

7392

Sample Input 3

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

Sample Output 3

4480

Sample Input 4

8
6 2
5 1
6 8
7 8
6 5
5 7
4 3
1 4
7 6
8 3
2 8
3 6
3 2
8 5
1 5
5 8

Sample Output 4

82060779

Sample Input 5

3
1 1
1 2
1 3
2 1
2 2
2 3

Sample Output 5

0

When there is no order of activation that satisfies the condition, the output should be 0.



Sample input:
2
1 1
1 2
2 1
2 2


Sample output:
8

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

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

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

    def unite(self, x, y):
        rx = self.find(x)
        ry = self.find(y)
        if rx != ry:
            dx = -self.table[rx]
            dy = -self.table[ry]
            if dx != dy:
                if dx < dy:
                    self.table[rx] = ry
                else:
                    self.table[ry] = rx
            else:
                self.table[rx] -= 1
                self.table[ry] = rx
        return


M = 10 ** 9 + 7
N = 0
F = [0]
edges = []


def solve(nodes):
    global edges

    pair_table = [0] * (2 * N)
    for v in nodes:
        if len(edges[v]) == 1:
            nv = edges[v].pop()
            pair_table[v] = nv
            edges[nv].remove(v)
            v, pv = nv, v
            while len(edges[v]) == 1:
                nv = edges[v].pop()
                pair_table[v] = nv
                edges[nv].remove(v)
                v, pv = nv, v

    v0 = 0
    for v in nodes:
        if len(edges[v]) != 0:
            v0 = v
            break
    [v1, v2] = edges[v0]

    r = 0
    for nv0 in [v1, v2]:
        nv, v = nv0, v0
        pair_table[v] = nv
        v, pv = nv, v
        while v != v0:
            [nv1, nv2] = edges[v]
            nv = nv1 if nv1 != pv else nv2
            pair_table[v] = nv
            v, pv = nv, v
        r += calc(nodes, pair_table)
        r %= M

    return r


def calc(nodes, pair_table):

    is_root = [True] * (2 * N)
    tree = [None] * (2 * N)
    counts = [0] * (2 * N)
    perms = [0] * (2 * N)

    for v in nodes:
        nv = pair_table[v]
        nnv = pair_table[nv]
        if v < nnv:
            is_root[v] = False
            if tree[nv] is None:
                tree[nv] = []
            tree[nv].append(v)

    c = 0
    for v in nodes:
        if is_root[v]:
            calc_node(v, tree, counts, perms)
            c += counts[v]
    p = F[c]
    for v in nodes:
        if is_root[v]:
            p *= powmod(F[counts[v]], M - 2, M)
            p %= M
            p *= perms[v]
            p %= M

    return p


def calc_node(node, tree, counts, perms):

    if tree[node] is None:
        counts[node] = 1
        perms[node] = 1
    else:
        c = 0
        for child in tree[node]:
            calc_node(child, tree, counts, perms)
            c += counts[child]
        counts[node] = c + 1
        p = F[c]
        for child in tree[node]:
            p *= powmod(F[counts[child]], M - 2, M)
            p %= M
            p *= perms[child]
            p %= M
        perms[node] = p

def powmod(a, x, m):
    y = 1
    while 0 < x:
        if x % 2 == 1:
            y *= a
            y %= m
        x //= 2
        a = a ** 2
        a %= M

    return y


def main():
    global F
    global N
    global edges

    N = int(input())
    balls = []
    for i in range(2 * N):
        na = list(map(int, input().split()))
        balls.append((na[0] - 1, N + na[1] - 1))

    p = 1
    for i in range(1, 2 * N + 1):
        p *= i
        p %= M
        F.append(p)

    uf = UnionFind(2 * N)
    edges = []
    for i in range(2 * N):
        edges.append([])

    for x, y in balls:
        uf.unite(x, y)
        edges[x].append(y)
        edges[y].append(x)


    ans = F[2 * N]

    for i in range(2 * N):
        if len(edges[i]) == 0:
            print(0)
            return

    groups = []
    for i in range(2 * N):
        groups.append(uf.find(i))

    for i in range(2 * N):
        if groups[i] == i:
            nodes = [v for v in range(2 * N) if groups[v] == i]
            num_nodes = len(nodes)
            edge_counts = [len(edges[v]) for v in nodes]
            num_edges = sum(edge_counts) // 2
            if num_nodes != num_edges:
                print(0)
                return
            ans *= powmod(F[num_nodes], M - 2, M)
            ans *= solve(nodes)
            ans %= M

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Time Limit Exceeded

Solution code:
#!/usr/bin/env python3

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

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

    def unite(self, x, y):
        rx = self.find(x)
        ry = self.find(y)
        if rx != ry:
            dx = -self.table[rx]
            dy = -self.table[ry]
            if dx != dy:
                if dx < dy:
                    self.table[rx] = ry
                else:
                    self.table[ry] = rx
            else:
                self.table[rx] -= 1
                self.table[ry] = rx
        return


M = 10 ** 9 + 7
N = 0
F = [0]
edges = []


def solve(nodes):
    global edges

    pair_table = [0] * (2 * N)
    for v in nodes:
        if len(edges[v]) == 1:
            nv = edges[v].pop()
            pair_table[v] = nv
            edges[nv].remove(v)
            v, pv = nv, v
            while len(edges[v]) == 1:
                nv = edges[v].pop()
                pair_table[v] = nv
                edges[nv].remove(v)
                v, pv = nv, v

    v0 = 0
    for v in nodes:
        if len(edges[v]) != 0:
            v0 = v
            break
    [v1, v2] = edges[v0]

    r = 0
    for nv0 in [v1, v2]:
        nv, v = nv0, v0
        pair_table[v] = nv
        v, pv = nv, v
        while v != v0:
            [nv1, nv2] = edges[v]
            nv = nv1 if nv1 != pv else nv2
            pair_table[v] = nv
            v, pv = nv, v
        r += calc(nodes, pair_table)
        r %= M

    return r


def calc(nodes, pair_table):

    is_root = [True] * (2 * N)
    tree = [None] * (2 * N)
    counts = [0] * (2 * N)
    perms = [0] * (2 * N)

    for v in nodes:
        nv = pair_table[v]
        nnv = pair_table[nv]
        if v < nnv:
            is_root[v] = False
            if tree[nv] is None:
                tree[nv] = []
            tree[nv].append(v)

    c = 0
    for v in nodes:
        if is_root[v]:
            calc_node(v, tree, counts, perms)
            c += counts[v]
    p = F[c]
    for v in nodes:
        if is_root[v]:
            p *= powmod(F[counts[v]], M - 2, M)
            p %= M
            p *= perms[v]
            p %= M

    return p


def calc_node(node, tree, counts, perms):

    if tree[node] is None:
        counts[node] = 1
        perms[node] = 1
    else:
        c = 0
        for child in tree[node]:
            calc_node(child, tree, counts, perms)
            c += counts[child]
        counts[node] = c + 1
        p = F[c]
        for child in tree[node]:
            p *= powmod(F[counts[child]], M - 2, M)
            p %= M
            p *= perms[child]
            p %= M
        perms[node] = p

def powmod(a, x, m):
    y = 1
    while 0 < x:
        if x % 2 == 1:
            y *= a
            y %= m
        x //= 2
        a = a ** 2
        a %= M

    return y


def main():
    global F
    global N
    global edges

    N = int(input())
    balls = []
    for i in range(2 * N):
        na = list(map(int, input().split()))
        balls.append((na[0] - 1, N + na[1] - 1))

    p = 1
    for i in range(1, 2 * N + 1):
        p *= i
        p %= M
        F.append(p)

    uf = UnionFind(2 * N)
    edges = []
    for i in range(2 * N):
        edges.append([])

    for x, y in balls:
        uf.unite(x, y)
        edges[x].append(y)
        edges[y].append(x)


    ans = F[2 * N]

    for i in range(2 * N):
        if len(edges[i]) == 0:
            print(0)
            return

    for i in range(2 * N):
        if uf.find(i) == i:
            nodes = [v for v in range(2 * N) if uf.find(v) == i]
            num_nodes = len(nodes)
            edge_counts = [len(edges[v]) for v in nodes]
            num_edges = sum(edge_counts) // 2
            if num_nodes != num_edges:
                print(0)
                return
            ans *= powmod(F[num_nodes], M - 2, M)
            ans *= solve(nodes)
            ans %= M

    print(ans)

if __name__ == '__main__':
    main()

Submission status: Accepted

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

MOD = 10**9 + 7

N = int(input())
ball = (tuple(int(x) for x in row.split()) for row in sys.stdin.readlines())

# x座標を1,2,...,N
# y座標をN+1,N+2,...,N+N

graph = [set() for _ in range(N+N+1)]
for x,y in ball:
    graph[x].add(y+N)
    graph[y+N].add(x)

visited = [False] * (N+N+1)
components = []
for x in range(1,N+N+1):
    if visited[x]:
        continue
    V = set([x])
    E = []
    q = [x]
    visited[x] = True
    while q:
        y = q.pop()
        for z in graph[y]:
            if y < z:
                E.append((y,z))
            if visited[z]:
                continue
            V.add(z)
            visited[z] = True
            q.append(z)
    components.append((V,E))

def make_get_pattern(V):
    deg1 = [x for x in V if len(graph[x]) == 1]
    get = {}
    while deg1:
        x = deg1.pop()
        if not graph[x]:
            continue
        y = graph[x].pop()
        se = graph[y]; se.remove(x)
        if len(se) == 1: deg1.append(y)
        if x < y:
            get[(x,y)] = 0
        else:
            get[(y,x)] = 1
    for x in V:
        if graph[x]:
            y = graph[x].pop()
            break
    # 残りはサイクル
    graph[y].remove(x)
    if x > y: x,y = y,x
    get[(x,y)] = 2
    while graph[x]:
        y = graph[x].pop()
        graph[y].remove(x)
        if x < y:
            get[(x,y)] = 3
        else:
            get[(y,x)] = 2
        x = y
    return get

def F(V,E):
    # V is connected
    if len(E) != len(V):
        return 0
    ret = 0
    E.sort()
    get = make_get_pattern(V)
    den1,den2 = 1,1
    dp1 = {x:0 for x in V}
    dp2 = {x:0 for x in V}
    for x,y in E:
        if get[(x,y)] == 0:
            k1 = dp1[x] + 1; k2 = dp2[x] + 1
        elif get[(x,y)] == 1:
            k1 = dp1[y] + 1; k2 = dp2[y] + 1
        elif get[(x,y)] == 2:
            k1 = dp1[x] + 1; k2 = dp2[y] + 1
        else:
            k1 = dp1[y] + 1; k2 = dp2[x] + 1
        dp1[x] += k1; dp1[y] += k1
        dp2[x] += k2; dp2[y] += k2
        den1 *= k1; den2 *= k2
        den1 %= MOD; den2 %= MOD
    return sum(pow(x,MOD-2,MOD) for x in (den1,den2))

prob = 1
for c in components:
    prob *= F(*c)
    prob %= MOD

answer = prob
for n in range(1,N+N+1):
    answer *= n
    answer %= MOD
print(answer)

Submission status: Accepted

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

MOD = 10**9 + 7

N = int(input())
ball = [tuple(int(x) for x in input().split()) for _ in range(N+N)]

# x座標を1,2,...,N
# y座標をN+1,N+2,...,N+N

graph = [set() for _ in range(N+N+1)]
for x,y in ball:
    graph[x].add(y+N)
    graph[y+N].add(x)

visited = set()
components = []
for x in range(1,N+N+1):
    if x in visited:
        continue
    V = set([x])
    q = [x]
    while q:
        y = q.pop()
        for z in graph[y]:
            if z in V:
                continue
            V.add(z)
            q.append(z)
    visited |= V
    components.append(V)

def make_get_patterns(V):
    deg1 = [x for x in V if len(graph[x]) == 1]
    get = {},{}
    while deg1:
        x = deg1.pop()
        if not graph[x]:
            continue
        y = graph[x].pop()
        se = graph[y]; se.remove(x)
        if len(se) == 1: deg1.append(y)
        if x < y:
            get[0][(x,y)] = 0; get[1][(x,y)] = 0
        else:
            pass
            get[0][(y,x)] = 1; get[1][(y,x)] = 1
    for x in V:
        if graph[x]:
            y = graph[x].pop()
            break
    # 残りはサイクル
    graph[y].remove(x)
    if x > y: x,y = y,x
    get[0][(x,y)] = 0; get[1][(x,y)] = 1
    while True:
        if not graph[x]:
            break
        y = graph[x].pop()
        graph[y].remove(x)
        if x < y:
            get[0][(x,y)] = 1; get[1][(x,y)] = 0
        else:
            get[0][(y,x)] = 0; get[1][(y,x)] = 1
        x = y
    return get

def F(V):
    # V is connected
    E = sorted((x,y) for x in V if x <= N for y in graph[x])
    if len(E) != len(V):
        return 0
    ret = 0
    for get in make_get_patterns(V):
        den = 1
        dp = {x:0 for x in V}
        for x,y in E:
            if get[(x,y)] == 0:
                k = dp[x] + 1
            else:
                k = dp[y] + 1
            dp[x] += k
            dp[y] += k
            den *= k
            den %= MOD
        ret += pow(den,MOD-2,MOD)
    return ret % MOD

prob = 1
for c in components:
    prob *= F(c)
    prob %= MOD

answer = prob
for n in range(1,N+N+1):
    answer *= n
    answer %= MOD
print(answer)

Submission status: Runtime Error

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

from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components

import time
start = time.time()

MOD = 10**9 + 7

N = int(input())
ball = (tuple(int(x) for x in row.split()) for row in sys.stdin.readlines())

# x座標を1,2,...,N
# y座標をN+1,N+2,...,N+N

graph = [set() for _ in range(N+N+1)]
for x,y in ball:
    graph[x].add(y+N)
    graph[y+N].add(x)

visited = [False] * (N+N+1)
components = []
for x in range(1,N+N+1):
    if visited[x]:
        continue
    V = set([x])
    E = []
    q = [x]
    visited[x] = True
    while q:
        y = q.pop()
        for z in graph[y]:
            if y < z:
                E.append((y,z))
            if visited[z]:
                continue
            V.add(z)
            visited[z] = True
            q.append(z)
    components.append((V,E))

def make_get_pattern(V):
    deg1 = [x for x in V if len(graph[x]) == 1]
    get = {}
    while deg1:
        x = deg1.pop()
        if not graph[x]:
            continue
        y = graph[x].pop()
        se = graph[y]; se.remove(x)
        if len(se) == 1: deg1.append(y)
        if x < y:
            get[(x,y)] = 0
        else:
            get[(y,x)] = 1
    for x in V:
        if graph[x]:
            y = graph[x].pop()
            break
    # 残りはサイクル
    graph[y].remove(x)
    if x > y: x,y = y,x
    get[(x,y)] = 2
    while graph[x]:
        y = graph[x].pop()
        graph[y].remove(x)
        if x < y:
            get[(x,y)] = 3
        else:
            get[(y,x)] = 2
        x = y
    return get

def F(V,E):
    # V is connected
    if len(E) != len(V):
        return 0
    ret = 0
    E.sort()
    get = make_get_pattern(V)
    den1,den2 = 1,1
    dp1 = {x:0 for x in V}
    dp2 = {x:0 for x in V}
    for x,y in E:
        if get[(x,y)] == 0:
            k1 = dp1[x] + 1; k2 = dp2[x] + 1
        elif get[(x,y)] == 1:
            k1 = dp1[y] + 1; k2 = dp2[y] + 1
        elif get[(x,y)] == 2:
            k1 = dp1[x] + 1; k2 = dp2[y] + 1
        else:
            k1 = dp1[y] + 1; k2 = dp2[x] + 1
        dp1[x] += k1; dp1[y] += k1
        dp2[x] += k2; dp2[y] += k2
        den1 *= k1; den2 *= k2
        den1 %= MOD; den2 %= MOD
    return sum(pow(x,MOD-2,MOD) for x in (den1,den2))

prob = 1
for c in components:
    prob *= F(*c)
    prob %= MOD

answer = prob
for n in range(1,N+N+1):
    answer *= n
    answer %= MOD
print(answer)

time.time()-start

Submission status: Runtime Error

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

MOD = 10**9 + 7

N = int(input())
ball = [tuple(int(x) for x in input().split()) for _ in range(N+N)]

U = N+N+10
fact = [1] * (U+1); fact_inv = [1] * (U+1)
for n in range(1,U+1):
    fact[n] = fact[n-1] * n % MOD
fact_inv[U] = pow(fact[U],MOD-2,MOD)
for n in range(U,0,-1):
    fact_inv[n-1] = fact_inv[n] * n % MOD

X_to_Y = [[] for _ in range(N+1)]
Y_to_X = [[] for _ in range(N+1)]
for x,y in ball:
    X_to_Y[x].append(y)
    Y_to_X[y].append(x)

# とりあえず連結成分に分けよう
visited_x = set()
visited_y = set()
components = []
for x,y in ball:
    if x in visited_x:
        continue
    V = set()
    V_x = set()
    V_y = set()
    q = [(x,y)]
    while q:
        x,y = q.pop()
        V.add((x,y))
        if x not in V_x:
            V_x.add(x)
            for t in X_to_Y[x]:
                q.append((x,t))
        if y not in V_y:
            V_y.add(y)
            for t in Y_to_X[y]:
                q.append((t,y))
        V_x.add(x)
        V_y.add(y)
    visited_x |= V_x
    visited_y |= V_y
    components.append((V,V_x,V_y))

def make_get_patterns(V_x,V_y):
    assert len(V) == len(V_x) + len(V_y)
    rest_xy = {x:set(X_to_Y[x]) for x in V_x}
    rest_yx = {y:set(Y_to_X[y]) for y in V_y}
    deg1_x = set(x for x in V_x if len(rest_xy[x]) == 1)
    deg1_y = set(y for y in V_y if len(rest_yx[y]) == 1)
    get = {},{}
    while deg1_x or deg1_y:
        while deg1_x:
            x = deg1_x.pop()
            y = rest_xy[x].pop()
            se = rest_yx[y]; se.remove(x)
            if len(se) == 1: deg1_y.add(y)
            elif len(se) == 0: deg1_y.remove(y)
            get[0][(x,y)] = 0; get[1][(x,y)] = 0
        while deg1_y:
            y = deg1_y.pop()
            x = rest_yx[y].pop()
            se = rest_xy[x]; se.remove(y)
            if len(se) == 1: deg1_x.add(x)
            elif len(se) == 0: deg1_x.remove(x)
            get[0][(x,y)] = 1; get[1][(x,y)] = 1
    for x in V_x:
        if rest_xy[x]:
            y = rest_xy[x].pop()
            break
    get[0][(x,y)] = 0; get[1][(x,y)] = 1
    rest_yx[y].remove(x); deg1_y.add(y)
    while deg1_x or deg1_y:
        while deg1_x:
            x = deg1_x.pop()
            y = rest_xy[x].pop()
            se = rest_yx[y]; se.remove(x)
            if len(se) == 1: deg1_y.add(y)
            elif len(se) == 0: deg1_y.remove(y)
            get[0][(x,y)] = 0; get[1][(x,y)] = 1
        while deg1_y:
            y = deg1_y.pop()
            x = rest_yx[y].pop()
            se = rest_xy[x]; se.remove(y)
            if len(se) == 1: deg1_x.add(x)
            elif len(se) == 0: deg1_x.discard(x)
            get[0][(x,y)] = 1; get[1][(x,y)] = 0
    return get

def F(V,V_x,V_y):
    # 連結成分上の順序がうまくいっている確率を返す
    if len(V) != len(V_x) + len(V_y):
        return 0
    V = sorted(V)
    ret = 0
    for get in make_get_patterns(V_x,V_y):
        den = 1
        dp_x = {x:0 for x in V_x}
        dp_y = {y:0 for y in V_y}
        for x,y in V:
            if get[(x,y)] == 0: # x軸でとる
                k = dp_x[x] + 1
            else:
                k = dp_y[y] + 1
            dp_x[x] += k
            dp_y[y] += k
            den *= k
            den %= MOD
        ret += pow(den,MOD-2,MOD)
    return ret % MOD

prob = 1
for c in components:
    prob *= F(*c)
    prob %= MOD
answer = prob * fact[N+N] % MOD
print(answer)

Submission status: Runtime Error

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

MOD = 10**9 + 7

N = int(input())
ball = [tuple(int(x) for x in input().split()) for _ in range(N+N)]

U = N+N+10
fact = [1] * (U+1); fact_inv = [1] * (U+1)
for n in range(1,U+1):
    fact[n] = fact[n-1] * n % MOD
fact_inv[U] = pow(fact[U],MOD-2,MOD)
for n in range(U,0,-1):
    fact_inv[n-1] = fact_inv[n] * n % MOD

X_to_Y = [[] for _ in range(N+1)]
Y_to_X = [[] for _ in range(N+1)]
for x,y in ball:
    X_to_Y[x].append(y)
    Y_to_X[y].append(x)

# とりあえず連結成分に分けよう
visited_x = set()
visited_y = set()
components = []
for x,y in ball:
    if x in visited_x:
        continue
    V = set()
    V_x = set()
    V_y = set()
    q = [(x,y)]
    while q:
        x,y = q.pop()
        V.add((x,y))
        if x not in V_x:
            V_x.add(x)
            for t in X_to_Y[x]:
                q.append((x,t))
        if y not in V_y:
            V_y.add(y)
            for t in Y_to_X[y]:
                q.append((t,y))
        V_x.add(x)
        V_y.add(y)
    visited_x |= V_x
    visited_y |= V_y
    components.append((V,V_x,V_y))

def make_get_patterns(V_x,V_y):
    assert len(V) == len(V_x) + len(V_y)
    rest_xy = {x:set(X_to_Y[x]) for x in V_x}
    rest_yx = {y:set(Y_to_X[y]) for y in V_y}
    deg1_x = set(x for x in V_x if len(rest_xy[x]) == 1)
    deg1_y = set(y for y in V_y if len(rest_yx[y]) == 1)
    get = {},{}
    while deg1_x or deg1_y:
        while deg1_x:
            x = deg1_x.pop()
            y = rest_xy[x].pop()
            se = rest_yx[y]; se.remove(x)
            if len(se) == 1: deg1_y.add(y)
            elif len(se) == 0: deg1_y.remove(y)
            get[0][(x,y)] = 0; get[1][(x,y)] = 0
        while deg1_y:
            y = deg1_y.pop()
            x = rest_yx[y].pop()
            se = rest_xy[x]; se.remove(y)
            if len(se) == 1: deg1_x.add(x)
            elif len(se) == 0: deg1_x.remove(x)
            get[0][(x,y)] = 1; get[1][(x,y)] = 1
    for x in V_x:
        if rest_xy[x]:
            y = rest_xy[x].pop()
            break
    get[0][(x,y)] = 0; get[1][(x,y)] = 1
    rest_yx[y].remove(x); deg1_y.add(y)
    while deg1_x or deg1_y:
        while deg1_x:
            x = deg1_x.pop()
            y = rest_xy[x].pop()
            se = rest_yx[y]; se.remove(x)
            if len(se) == 1: deg1_y.add(y)
            elif len(se) == 0: deg1_y.remove(y)
            get[0][(x,y)] = 0; get[1][(x,y)] = 1
        while deg1_y:
            y = deg1_y.pop()
            x = rest_yx[y].pop()
            se = rest_xy[x]; se.remove(y)
            if len(se) == 1: deg1_x.add(x)
            elif len(se) == 0: deg1_x.discard(x)
            get[0][(x,y)] = 1; get[1][(x,y)] = 0
    return get

def F(V,V_x,V_y):
    # 連結成分上の順序がうまくいっている確率を返す
    if len(V) != len(V_x) + len(V_y):
        return 0
    V = sorted(V)
    ret = 0
    for get in make_get_patterns(V_x,V_y):
        den = 1
        dp_x = {x:0 for x in V_x}
        dp_y = {y:0 for y in V_y}
        for x,y in V:
            if get[(x,y)] == 0: # x軸でとる
                k = dp_x[x] + 1
            else:
                k = dp_y[y] + 1
            dp_x[x] += k
            dp_y[y] += k
            den *= k
        ret += pow(den,MOD-2,MOD)
    return ret % MOD

prob = 1
for c in components:
    prob *= F(*c)
    prob %= MOD
answer = prob * fact[N+N] % MOD
print(answer)