/* 0440949 Andreas van Cranenburgh <andreas@unstable.nl>
 *
 * Data structures, assignment 5
 * */
    
import java.util.*;

public class Maze {
	public static final void main(String[] args) {
		Graph m = readMaze();
		// dijkstra(m, start, finish);
	}

	public static final Graph readMaze() {
		int n, first, last;
		Graph m = new Graph();

		/* scan the standard input for maze data */
		Scanner sc = new Scanner(System.in);

		/* number of rings */
		n = sc.nextInt();

		/* get positions of doors */
		for (int a = 0; a < n; a++) {
			Scanner ring = new Scanner(sc.nextLine());
			while(ring.hasNextInt()) {
				int b = ring.nextInt();
				int c = ring.nextInt();
				m.add(new Vertex(a, b, c));
			}
		}

		/* get positions of walls */
		for (int a = 0; a < (n-1); a++) {
			Scanner ring = new Scanner(sc.nextLine());
			if (ring.hasNextInt()) {
				first = ring.nextInt();
				last = first;
			} else
				break;
			while(ring.hasNextInt()) {
				int b = ring.nextInt();
				// last - b contains coordinates of compartment
				java.util.List adjacentDoors = new java.util.LinkedList(); 
				for (int c = 0; c < m.vertices.size(); c++)
					if (Math.abs(m.get(c).ring - a) <= 1)
						if (m.get(c).left >= last && m.get(c).right <= b) {
							// connect this door with all previous doors
							// (cartesian product minus reflexive links)
							for (int d = 0; c < adjacentDoors.size(); d++)
								m.add(new Edge(m.get(c), adjacentDoors.get(d)));
							adjacentDoors.add(m.get(c));
						}
			}
		}
	}
}
