Vocabulary Quiz

시간 제한2초메모리 제한2048 MB

요약
각 단어를 읽을 때 접두사만으로 단어를 구별할 수 있게 되는 지점까지 읽은 글자 수를 구해 순서대로 출력한다.
난이도

어려움10점 중 8점

유형
트라이, 트리, DFS, 구현
정답자
아직 제출이 없습니다

문제

Bessie is helping Elsie with her upcoming vocabulary quiz. The words to be tested will be drawn from a bank of MM distinct words, where no word in the bank is a prefix of another word in the bank.

While the bank is nonempty, Bessie will select a word from the bank, remove it from the bank, and read it to Elsie one character at a time from left to right. Elsie's task is to tell Bessie once she can uniquely identify it, after which Bessie will stop reading.

Bessie has already decided to read the words from the word bank in the order w_1,w_2,…,w_Mw\_1,w\_2,\dots,w\_M. If Elsie answers as quickly as possible, how many characters of each word will Bessie read?

The words are given in a compressed format. We will first define N+1N+1 (1≤N≤1061\le N\le 10^6) distinct words, and then the word bank will consist of all those words that are not a prefix of another word. The words are defined as follows:

  • Initially, the 00th word will be the empty string.
  • Then for each 1≤i≤N1\le i\le N, the iith word will be equal to the p_ip\_ith word plus an additional character at the end (0≤p_i\<i0\le p\_i\<i). The characters are chosen such that all N+1N+1 words are distinct.

입력

The first line contains NN, where N+1N+1 is the number of words given in the compressed format.

The next line contains p_1,p_2,…,p_Np\_1,p\_2,\dots,p\_N where p_ip\_i represents that the ii-th word is formed by taking the p_ip\_i-th word and adding a single character to the end.

Let MM be the number of words that are not a prefix of some other word. The next MM lines will contain w_1,w_2,…,w_Mw\_1,w\_2,\dots,w\_M, meaning that the w_iw\_ith word will be the iith to be read. It is guaranteed that the words to be read form a permutation of the words in the word bank.

출력

Output MM lines, where the iith line contains the number of characters of the iith word that Bessie reads.

예제3

  1. 예제 1

    입력
    5
    0 1 2 3 4
    5
    
    예상 출력
    0
    
  2. 예제 2

    입력
    4
    0 0 1 1
    4
    3
    2
    
    예상 출력
    2
    1
    0
    
  3. 예제 3

    입력
    4
    0 0 1 1
    2
    3
    4
    
    예상 출력
    1
    2
    0