Decide whether some sequence of red and green moves brings robots starting on every intersection together onto one intersection.
Medium7GraphBFSNo attempts yetTime limit2sMemory limit256 MBWhile you were not watching, your N robots started moving on their own and spread across your hometown. The town has N intersections numbered 0 through N−1, and exactly one robot stands on each intersection. Intersection i carries one red signpost that points at an intersection ri=i and one green signpost that points at an intersection gi=i.
When you press the red button on the remote control, every robot moves along the red signpost at the same time: a robot on intersection i moves to ri. When you press the green button, every robot moves to gi instead. Write a program that decides whether some sequence of button presses brings all N robots to the same intersection at the same time.
The first line contains the number of data sets P (1≤P≤500). The data sets are independent and are processed the same way.
Each data set consists of three lines.
2≤N≤500, and the sum of N over all data sets is at most 2000. Both signposts on an intersection may point the same way, so ri=gi is possible.
Print one line per data set. The line contains the data set number K, one space, then YES if you can gather every robot on one intersection, or NO otherwise.
In the second data set of the example, pressing GREEN, RED, RED, GREEN gathers every robot on intersection 2.