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.
Hard8GraphTopological sortGreedySimulationNo attempts yetTime limit20sMemory limit512 MBYou are playing a solitaire game with N stacks of face-up cards. Every stack starts with exactly C 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.
You win if some sequence of moves leaves every stack with at most one card. Given the starting arrangement, decide whether you can win.
The first line has one integer P, the number of premade stacks that the test cases draw from. Each of the next P lines describes one premade stack. The i-th of those lines starts with Ci, the number of cards in the i-th premade stack, and continues with Ci ordered pairs of integers. The j-th pair, Vij and Sij, is the value and the suit of the j-th card from the top of that stack.
The next line has one integer T, the number of test cases. Each test case takes two lines. The first line has two integers N and C, the number of stacks and the number of cards in each stack. The second line has N integers Pi, the indexes of the premade stacks that form the board, numbered from 0.
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.
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.