Dad's Card Trick
Time limit1sMemory limit256 MB
For each test case with N cards and K face up, compute the fewest moves and flips that force both decks to hold equal face-up counts whatever the layout.
- Level
Hard8 of 10
- Topics
- Math, Combinatorics
- Solved
- No attempts yet
Problem
You show off card tricks so often that your family is worn out. To put a stop to it, your dad picks a trick he believes you cannot do.
He blindfolds you and hands you a deck of cards. He tells you that exactly of them are face up, but not which ones. A second deck starts out empty.
Here is the goal. After the last operation the two decks have to hold the same number of face-up cards. That number does not have to be . You are blindfolded and cannot see the arrangement, so one sequence of operations has to succeed for every possible initial arrangement of the face-up cards.
You may perform the following two operations in any order, any number of times.
- Move one card from one deck to the other.
- Flip one card in either deck. A face-up card becomes face down, and a face-down card becomes face up.
To impress your dad you accepted the challenge, and you decided to find the shortest possible sequence of operations. Write a program that computes its length.
Input
The first line contains a single integer , the number of test cases. Each of the following lines contains two integers and , separated by a space.
Output
For each test case, print on one line the minimum number of operations needed to reach the goal. If the goal cannot be reached, print instead.