# Define the blocks with the special square at (0,0) and other squares relative to it
# Special square is at (0,0) in each block definition
BLOCKS = [
    [(0, 0), (-1, 0), (-1, -1), (0, -1)],  # Block 0 (2x2 square, special at bottom right)
    [(0, 0), (-1, 0), (0, -1)],  # Block 1 (L shape with special at corner)
    [(0, 0), (0, -1), (0, -2), (-1, 0)],  # Block 2 (horizontal L shape)
    [(0, 0), (0, -1), (0, -2), (0, -3)],  # Block 3 (horizontal line with special at end)
    [(0, 0), (-1, 0), (-1, -1), (-2, 0)]  # Block 4 (zigzag shape with special at corner)
]


def rotate_block(block, rotation):
    """Rotate block by 0, 90, 180, or 270 degrees clockwise."""
    if rotation == 0:
        return block
    elif rotation == 1:  # 90 degrees
        return [(col, -row) for row, col in block]
    elif rotation == 2:  # 180 degrees
        return [(-row, -col) for row, col in block]
    else:  # 270 degrees
        return [(-col, row) for row, col in block]


def create_grid(n):
    """Create an empty grid of size n x n."""
    return [[0 for _ in range(n)] for _ in range(n)]


def copy_grid(grid):
    """Create a deep copy of the grid."""
    return [row[:] for row in grid]


def can_place_block(grid, block, x, y):
    """Check if a block can be placed at position (x, y)."""
    n = len(grid)
    for row, col in block:
        r, c = x + row - 1, y + col - 1  # Convert to 0-indexed
        if r < 0 or r >= n or c < 0 or c >= n or grid[r][c] == 1:
            return False
    return True


def place_block(grid, block, x, y):
    """Place a block at position (x, y)."""
    for row, col in block:
        r, c = x + row - 1, y + col - 1  # Convert to 0-indexed
        grid[r][c] = 1
    return grid


def is_row_filled(grid, row):
    """Check if a row is completely filled."""
    return all(cell == 1 for cell in grid[row])


def is_col_filled(grid, col):
    """Check if a column is completely filled."""
    return all(grid[row][col] == 1 for row in range(len(grid)))


def clear_rows_and_columns(grid):
    """Clear filled rows and columns."""
    n = len(grid)
    rows_to_clear = []
    cols_to_clear = []

    # Find rows and columns to clear
    for i in range(n):
        if is_row_filled(grid, i):
            rows_to_clear.append(i)
        if is_col_filled(grid, i):
            cols_to_clear.append(i)

    # Clear the rows and columns
    for row in rows_to_clear:
        for col in range(n):
            grid[row][col] = 0

    for col in cols_to_clear:
        for row in range(n):
            grid[row][col] = 0

    return grid, rows_to_clear, cols_to_clear


def sum_row(grid, row):
    """Sum of cells in a row."""
    return sum(grid[row])


def sum_col(grid, col):
    """Sum of cells in a column."""
    return sum(grid[row][col] for row in range(len(grid)))


def count_filled_cells(grid):
    """Count the number of filled cells in the grid."""
    return sum(sum(row) for row in grid)


def visualize_grid(grid, title="Current Grid"):
    """Visualize the grid in ASCII."""
    n = len(grid)
    print(f"\n{title}:")
    print("  " + " ".join(str(i + 1) for i in range(n)))
    for i, row in enumerate(grid):
        print(f"{i + 1} " + " ".join("█" if cell == 1 else "·" for cell in row))
    print()


def visualize_block(block, block_idx, rotation):
    """Visualize a block."""
    # Find the min and max coordinates to determine the size of the visualization
    min_row = min(row for row, _ in block)
    max_row = max(row for row, _ in block)
    min_col = min(col for _, col in block)
    max_col = max(col for _, col in block)

    # Create a visualization grid
    rows = max_row - min_row + 1
    cols = max_col - min_col + 1

    # Adjust the grid to account for negative indices
    viz_grid = [[" " for _ in range(cols)] for _ in range(rows)]

    # Fill in the block cells
    for r, c in block:
        viz_grid[r - min_row][c - min_col] = "█"

    # Print the block info
    print(f"\nBlock {block_idx} (rotation: {rotation * 90}°):")
    for row in viz_grid:
        print("".join(row))
    print()


def find_best_position(grid, block, visualize=False):
    """Find the best position to place the block using a heuristic."""
    n = len(grid)
    best_score = -1
    best_pos = None

    # Define a scoring heuristic that prefers:
    # 1. Positions that potentially fill rows/columns
    # 2. Positions that place blocks along edges or in corners
    for x in range(1, n + 1):
        for y in range(1, n + 1):
            if can_place_block(grid, block, x, y):
                # Calculate how many cells this placement would add to nearly complete rows/columns
                score = 0
                temp_grid = copy_grid(grid)

                for row, col in block:
                    r, c = x + row - 1, y + col - 1  # Convert to 0-indexed
                    if 0 <= r < n and 0 <= c < n:
                        temp_grid[r][c] = 1

                        # Give higher score for nearly complete rows/columns
                        row_sum = sum_row(temp_grid, r)
                        col_sum = sum_col(temp_grid, c)
                        score += (row_sum / n) ** 2 + (col_sum / n) ** 2

                        # Bonus for edges and corners
                        if r == 0 or r == n - 1 or c == 0 or c == n - 1:
                            score += 0.5
                            if (r == 0 and c == 0) or (r == 0 and c == n - 1) or (r == n - 1 and c == 0) or (
                                    r == n - 1 and c == n - 1):
                                score += 0.5

                # Check if this placement would clear any rows/columns
                filled_before = count_filled_cells(temp_grid)
                temp_grid_after_clear, _, _ = clear_rows_and_columns(copy_grid(temp_grid))
                filled_after = count_filled_cells(temp_grid_after_clear)
                cleared_cells = filled_before - filled_after

                if cleared_cells > 0:
                    # Placing a block that clears rows/columns is highly desirable
                    score += cleared_cells * 5

                if score > best_score:
                    best_score = score
                    best_pos = (x, y)

    return best_pos


def solve_block_game(n, a, b, c, d, e, f, max_moves=10000, visualize=False):
    """Solve the Block game."""
    grid = create_grid(n)
    moves = []

    if visualize:
        visualize_grid(grid, "Initial Grid")

    # Initialize c and f at the start
    current_c, current_f = c, f
    move_number = 1

    while len(moves) < max_moves:
        # Generate the next block
        current_c = (current_c ^ a) + b
        current_f = (current_f ^ d) + e
        block_idx = current_c % 5
        rotation = current_f % 4

        block = rotate_block(BLOCKS[block_idx], rotation)

        if visualize:
            print(f"\n--- Move {move_number} ---")
            visualize_block(block, block_idx, rotation)

        # Find the best position to place the block
        pos = find_best_position(grid, block, visualize)

        # If we can't place the block, end the game
        if pos is None:
            if visualize:
                print("No valid position found. Game over!")
            break

        x, y = pos
        moves.append((x, y))

        if visualize:
            print(f"Placing block at position ({x}, {y}):")

            # Create a preview grid to show where the block will be placed
            preview_grid = copy_grid(grid)
            for row, col in block:
                r, c = x + row - 1, y + col - 1  # Convert to 0-indexed
                if 0 <= r < n and 0 <= c < n:
                    preview_grid[r][c] = 1
            visualize_grid(preview_grid, "Grid after placement")

        # Place the block
        grid = place_block(grid, block, x, y)

        # Clear filled rows/columns
        grid, cleared_rows, cleared_cols = clear_rows_and_columns(grid)

        if visualize:
            if cleared_rows or cleared_cols:
                print(f"Cleared rows: {cleared_rows}")
                print(f"Cleared columns: {cleared_cols}")
                visualize_grid(grid, "Grid after clearing")
            else:
                print("No rows or columns cleared.")

        move_number += 1

    if visualize:
        print(f"\nGame finished with {len(moves)} moves.")
        visualize_grid(grid, "Final Grid")
        filled_cells = count_filled_cells(grid)
        print(f"Total filled cells: {filled_cells} ({filled_cells / (n * n):.2%} of grid)")

    return moves


def write_output(moves, output_file="block.out"):
    """Write the moves to an output file."""
    with open(output_file, "w") as f:
        f.write(f"{len(moves)}\n")
        for x, y in moves:
            f.write(f"{x} {y}\n")


def main(debug=False):
    # Read input
    with open("block.in", "r") as f:
        n, a, b, c, d, e, f = map(int, f.readline().split())

    # Solve the game
    moves = solve_block_game(n, a, b, c, d, e, f, visualize=debug)

    # Write output
    write_output(moves, "block.out")

    if debug:
        print(f"Wrote {len(moves)} moves to block.out")


if __name__ == "__main__":
    main(False)
