| 시간 제한 | 메모리 제한 | 제출 | 정답 | 맞힌 사람 | 정답 비율 |
|---|---|---|---|---|---|
| 1 초 | 1024 MB | 37 | 23 | 22 | 78.571% |
A card game similar to Old Maid is played by n players P1, ..., and Pn, sitting clockwise in this order.
For this game, n pairs of cards numbered 1 through n are used. Each player has two cards at hand to start with.
First, any player who has a pair of cards with the same number discards them. If by chance all the players discard the cards in hand, the game ends. Otherwise, the following actions are repeated until the game ends. Note that, from now on, for a player p, the next player means the player closest to p in the clockwise direction among those who still have one or more cards at that point in time.
Figure B-1 shows the initial hands of the three players of the second dataset in Sample Input. Immediately after, the player P1 discards the two cards in the hand. p of the first turn is P2 because P1 has no cards.
Figure B-1: The initial hands of the second dataset in Sample Input
Figure B-2 shows the hands of the five players of the last dataset in Sample Input after the following actions:
After this, P1 draws the only remaining card in P5's hand and discards the drawn card and the card with the same number 2 in the hand. The player to be drawn from the hand next is the next player of P5, which is P2 because P1's hand is empty now.
Figure B-2: The hands of the last dataset in Sample Input after the fourth turn
Since at least one pair of cards is discarded between two drawings from the hand of the same player, the game will end sooner or later. Unlike Old Maid, no cards will be left in the hand of any player at the end.
Write a program that, for given initial hands of all the players, computes the number of times cards are drawn by the end of the game.
The input consists of multiple datasets, each in the following format.
n c1,1 c1,2 ⋮ cn,1 cn,2
n is the number of players. n is an integer no less than two and no more than 1000. ci,1 and ci,2 are the numbers on the two cards in the initial hand of Pi (1 ≤ i ≤ n). Each integer between 1 and n, inclusive, appears exactly twice in c1,1, c1,2, ..., cn,1, and cn,2.
The end of the input is indicated by a line containing a zero. The input has at most 10000 lines.
For each dataset, output a single line containing the integer that is the number of times cards are drawn.
3 1 1 2 2 3 3 3 1 1 2 3 3 2 3 1 3 2 1 3 2 5 1 5 5 4 4 3 3 2 2 1 5 1 2 3 5 4 3 1 4 5 2 5 1 2 3 5 4 3 5 4 1 2 0
0 2 3 14 8 8
ICPC > Regionals > Asia Pacific > Japan > Japan Domestic Contest > 2022 Japan Domestic Contest B번