Locks and Keys
Time limit2sMemory limit128 MB
Determine reachability on a tree with colored locks and single-use keys held one at a time, requiring a search over reachable key/room states.
- Level
Medium7 of 10
- Topics
- DFS, Graph, Simulation
- Solved
- No attempts yet
Problem
The wizard Jaehwan is trapped in a maze of rooms and doors. Each door connects two rooms in both directions, and it is always possible to travel from any room to any other room (so the maze is a tree). There are locks in distinct colors and keys in the same colors. Each door may be locked by at most one lock, and each room may hold at most one key; every color has exactly one lock and exactly one key.
Jaehwan is a wizard and could normally open locks by magic, but he left his spellbook behind, so right now he cannot use magic at all.
He is currently in room and wants to reach room , where the spellbook is. In one step he can move from his current room to an adjacent room through a door. If a door is locked, he can open it and pass only while holding a key of the same color as the lock. Once a door has been opened it stays open, so he may pass through it freely afterwards.
Jaehwan can hold only one key at a time. He may not set a key down in another room to reuse it later, and opening a locked door consumes the key (it disappears).
Given the structure of the maze and the positions of the keys and locks, determine whether Jaehwan can travel from room to room .
Input
The input consists of several test cases.
The first line of each test case contains four integers , , , and : the number of rooms (), the number of locks (and keys) (), and the numbers of the start room and the destination room . Rooms are numbered from to .
The next numbers give, in increasing order of color (color through color ), the room that holds the key of that color.
The following lines each describe a door as . If , the door between rooms and is locked by the lock of color ; if , the door is not locked.
The last line of the input is 0 0 0 0.
Output
For each test case, print a single line: Possible if Jaehwan can travel from room to room , and Impossible otherwise.