#P9760. [COCI 2022/2023 #3] Skrivača

[COCI 2022/2023 #3] Skrivača

Problem Description

Marin and Luka are playing a popular children's game—hide-and-seek—in their house. The house has nn rooms, and there are mm pairs of rooms connected by a door. The rooms are numbered from 11 to nn, and there is a path between every two rooms.

Luka came up with a hiding strategy: when Marin enters room vv, Luka will hide in room ava_v. At the start of the game, Marin chooses the room v0v_0 where she starts searching, and Luka hides in room av0a_{v_0}. In each round of the game, Marin first chooses a room uu adjacent to her current room and enters it. Then Luka knows that Marin is in room uu, so according to his hiding strategy he will hide in room aua_u. Note that Luka may choose any route to reach room aua_u, and in one round he may pass through any number of rooms.

We say Marin finds Luka when both of them are in the same room; at that moment the game ends.

Marin has discovered Luka's hiding strategy, so she wants you to determine, for each starting room, whether she can find Luka in a finite number of rounds. If she can, compute the minimum number of rounds needed under optimal play (Marin tries to minimize the number of rounds, Luka tries to maximize it).

Input Format

The first line contains two integers n,mn,m, representing the number of rooms and the number of connected pairs of rooms.

The second line contains nn integers aia_i, representing Luka's hiding strategy.

In the next mm lines, each line contains two integers xi,yix_i,y_i, indicating that these two rooms are connected. There is at most one direct connection between any two rooms.

Output Format

Output one line with nn numbers, representing the minimum number of rounds needed. If the game cannot end in a finite number of rounds, output 1-1.

4 4
3 4 1 2
1 2
2 3
3 4
4 1
-1 -1 -1 -1
8 9
2 3 2 1 6 5 6 7
1 2
1 3
2 4
3 4
4 5
4 6
6 7
5 7
4 8
1 2 2 2 1 1 1 1
9 8
1 9 1 1 1 9 9 9 1
1 2
2 3
3 4
4 5
5 6
6 7
7 8
8 9
0 1 1 2 1 1 2 1 1

Hint

Sample Explanation #2.

In the first round, Marin goes from room 44 to room 88, and in the second round she goes back to room 44. Luka must pass through room 44 to get from room 77 to room 11. Therefore, Marin can find him in two rounds.

Constraints.

Subtask Points Special Properties
11 1515 n1000,m2000n\le 1000,m\le2000
22 2525 m=n1m=n-1
33 3030 Luka's hiding strategy satisfies that he will never hide in a room adjacent to or the same as Marin's current room, and the structure of the house satisfies that the game can end with at most 55 different rooms, independent of Luka's hiding strategy.
44 4040 No special properties.

For 100%100\% of the testdata, 1n2×1051\leq n \leq 2\times10^5, $n-1\le m\le \min(5\times 10^5,\dfrac{n\times (n-1)}{2})$, 1ai,xi,yin1\le a_i,x_i,y_i\le n, xiyix_i\neq y_i.

The full score for this problem is 110110 points.

Translated by ChatGPT 5