Stack Management (Large)
Time limit20sMemory limit512 MB
Given several stacks of cards, decide whether a sequence of suit-based removals and moves to empty stacks can reduce every stack to at most one card.
- Level
Hard8 of 10
- Topics
- Graph, Topological sort, Greedy, Simulation
- Solved
- No attempts yet
Problem
You are playing a solitaire game with stacks of face-up cards. Every stack starts with exactly cards. Each card has a value and a suit, and no two cards in the game share the same value and suit.
One move is one of the following.
- If two or more cards of the same suit are on top of different stacks, you may remove the smallest-valued one of those cards from the game. A stack that loses its last card is still in play. It just becomes empty.
- If some stack is empty, you may take the top card of any non-empty stack and put it on that empty stack, where it becomes the only card.
You win if some sequence of moves leaves every stack with at most one card. Given the starting arrangement, decide whether you can win.
Input
The first line has one integer , the number of premade stacks that the test cases draw from. Each of the next lines describes one premade stack. The -th of those lines starts with , the number of cards in the -th premade stack, and continues with ordered pairs of integers. The -th pair, and , is the value and the suit of the -th card from the top of that stack.
The next line has one integer , the number of test cases. Each test case takes two lines. The first line has two integers and , the number of stacks and the number of cards in each stack. The second line has integers , the indexes of the premade stacks that form the board, numbered from 0.
Output
For each test case, print one line of the form Case #x: y, where x is the test case number starting from 1, and y is POSSIBLE if you can win the game and IMPOSSIBLE if you cannot.
Limits
- The -th premade stack has exactly cards.
- No two cards in a test case have the same value and suit.
Notes
In the first case of the sample there are two stacks of two cards each. The first stack has the 7 of suit 2 on top and the 7 of suit 1 below it. The second stack has the 3 of suit 2 on top and the 6 of suit 2 below it. One winning line is: remove the 3 of suit 2, then remove the 6 of suit 2, which empties the second stack, then move the 7 of suit 2 onto that empty stack. Every stack now holds at most one card.
In the second case of the sample there are three stacks of two cards each. The only legal move removes the 5 of suit 4, and no new move opens up after it.