Fox Buki

시간 제한2초메모리 제한2048 MB

요약
n명의 팬이 각각 n장씩 나눠 가진 n^2장의 카드를 교환해 모든 팬이 각 유형을 한 장씩 갖도록 만들되, 한 카드가 참여하는 교환 횟수의 최댓값이 최소가 되도록 교환 순서를 출력한다.
난이도

어려움10점 중 9점

유형
그리디, 구현, 그래프, 조합론
정답자
아직 제출이 없습니다

문제

In celebration of the galaxy-famous idol Fox Buki, a group of enthusiastic fans is curating her trading card collection. There are nn fans and n2n^2 distinct cards labeled 00 through n2−1n^2 − 1. The type of card ii is ⌊i/n⌋\lfloor i/n \rfloor, the integer quotient when ii is divided by nn, so each type t∈0,1,…,n−1t \in \\{0, 1, \dots , n − 1\\} appears in exactly nn cards.

Initially, the n2n^2 cards are partitioned among the fans so that each fan holds exactly nn cards. Starting from the initial distribution, the fans aim to rearrange the cards by performing a sequence of valid swaps so that every fan ends up with exactly one card of each type.

A swap is a pair (a,b)(a, b) of integers with 0≤a<b≤n2−10 ≤ a < b ≤ n^2 − 1; executing it swaps the cards labeled aa and bb. When the swap occurs, the two cards must be held by different fans.

To reduce wear and tear on the corners of the cards during the swap processing, the fans need to follow the preservation rule: no single card should be involved in too many swaps. For each card cc, let usage(c)\text{usage}(c) be the number of swaps involving cc. Among all sequences of valid swaps that end with each fan holding exactly one card of each type, minimize max⁡_0≤c≤n2−1usage(c)\max\_{0 \le c \le n^2-1}\text{usage}(c). Note that the total number of swaps need not be minimized.

Given the labels of the cards initially held by nn fans, write a program to output such a sequence of swaps. It is shown that there is such an optimal sequence of at most n3n^3 swaps.

입력

Your program is to read from standard input. The first line contains an integer nn (1≤n≤1001 ≤ n ≤ 100).

The following nn lines describe the initial holdings. The ii-th line among these nn lines contains nn distinct integers—the labels of the cards initially held by ii-th fan—listed in increasing order. These nn lists of integers form a partition of 0,1,…,n2−1\\{0, 1, \dots , n^2 − 1\\}.

출력

Your program is to write to standard output. Print an integer kk (0≤k≤n30 ≤ k ≤ n^3), the number of swaps.

Then print kk lines, each containing two integers aa and bb (0≤a<b≤n2−10 ≤ a < b ≤ n^2 − 1), describing the swaps (a,b)(a, b) in order. After performing these swaps:

  • Each fan should hold exactly one card of each type.
  • The maximum per-card usage should be the minimum.

If there are multiple valid solutions, anyone will be accepted.

예제3

  1. 예제 1

    입력
    2
    0 1
    2 3
    
    예상 출력
    1
    1 2
    
  2. 예제 2

    입력
    2
    0 3
    1 2
    
    예상 출력
    0
    
  3. 예제 3

    입력
    3
    0 2 8
    1 6 7
    3 4 5
    
    예상 출력
    3
    2 3
    4 6
    0 1