#P15804. [GESP202603 八级] 消息查找
[GESP202603 八级] 消息查找
Background
Related multiple-choice and true/false problems: https://ti.luogu.com.cn/problemset/1212.
Problem Description
There are messages in A's chat history, numbered in order. A message with a smaller number was sent earlier than a message with a larger number.
A message may quote a message with a smaller number, or it may quote nothing. A noticed that the number of messages that contain quotes will not be very large. An example of a chat history is:
- [Message 1] A: Has anyone done today's first problem?
- [Message 2] A: I got WA on the first problem, what could be the reason?
- [Message 3: quoting message 1] B: Me me me
- [Message 4: quoting message 2] C: I also got WA
- [Message 5: quoting message 2] B: Did you forget to use long long?
- [Message 6: quoting message 5] A: After changing it, I got AC. That's awesome!
For message (), A uses to mark whether message has a quote and the message number it quotes. If , then message quotes message ; if , then message quotes no message.
There are a lot of messages in the chat history. To quickly find the needed messages, A plans to implement a simple message search tool. At any moment, the tool can be positioned at exactly one message. If it is currently at message (), then next you may choose one of the following two operations:
- Move to message .
- If message quotes message , move to message .
You may perform the operations any number of times (including zero times).
A has queries. In the -th query (), A gives message numbers (). A wants to know: if the tool is currently at , what is the minimum number of operations needed to move to .
Input Format
The first line contains two positive integers , representing the number of messages and the number of queries.
The second line contains non-negative integers , describing the quoting relationships. The meaning is as described above.
Each of the next lines, the -th line () contains two positive integers , representing one query.
It is guaranteed that there are at most 1000 messages that contain quotes.
Output Format
Output lines. Each line contains one integer, representing the minimum number of operations needed to switch from message to message .
6 3
0 0 1 2 2 5
4 1
6 2
6 3
2
2
3
5 5
0 0 0 1 3
4 1
4 2
5 1
5 2
5 3
1
2
2
2
1
Hint
Constraints
For of the test points, it is guaranteed that and .
For all test points, it is guaranteed that , , , , and there are at most 1000 messages that contain quotes.
Translated by ChatGPT 5