Forgetful Waiter
Time limit1sMemory limit128 MB
Customers sit around a round table and pass pizzas left or right each turn; find the minimum number of turns until every pizza reaches the customer who ordered it.
- Level
Hard9 of 10
- Topics
- Graph, Greedy, Simulation, Implementation
- Solved
- No attempts yet
Problem
Bob is a waiter at Pizza Round, a restaurant that serves many kinds of pizza on round tables of different sizes. When a group of customers arrives, Bob seats them at a table of the right size, takes their orders, and later serves the pizzas by placing them in front of the customers so that each customer receives the type of pizza they ordered.
Unfortunately, Bob is forgetful and cannot remember what each customer ordered, so he usually puts the pizzas down in the wrong places. The customers kindly cooperate, passing the pizzas around the table over several turns until everyone has the right one. In each turn, a customer may pick up a pizza in front of them with their left hand and pass it to the neighbor on their left, and/or pick up a pizza with their right hand and pass it to the neighbor on their right (both hands may be used in the same turn). At most 5 pizzas may sit in front of any customer at once, so a pizza can be passed to a neighbor only when that neighbor still has room.
Given the type each customer ordered and the type currently in front of each customer, find the minimum number of turns needed until every customer has the pizza they ordered. This is always possible: for each type, the number of pizzas of that type on the table equals the number ordered. Only the minimum number of turns matters, not the exact passing strategy.
For example, six customers sit around a round table; the label on each customer is the type they ordered, and the number on each pizza is its type. The pizzas can be delivered in two turns, but not in one, because the single type-2 pizza needs at least two turns to reach its destination.

Write a program that computes the minimum number of turns needed to bring every pizza on the table to the customer who ordered it.
Input
The input contains several test cases. Each test case begins with a line holding an integer , the number of customers in the group (). The customers are numbered from to and sit around the table in counter-clockwise order, so customer is adjacent to customer . Each of the next lines describes one customer: line contains two integers and (), where is the pizza type customer ordered and is the pizza type currently placed in front of customer . The sequence is a permutation of . A line containing a single terminates the input.
Output
For each test case, print a single line containing one non-negative integer: the minimum number of turns required to bring every pizza to the customer who ordered it. If the pizzas are already placed correctly, print .