Bacon Number

시간 제한1초메모리 제한1024 MB

요약
각 영화에 출연한 배우 목록이 주어질 때, 두 배우를 연결하는 배우와 영화의 교대 경로를 찾아 출력하거나 경로가 없으면 -1을 출력한다.
난이도

보통10점 중 6점

유형
그래프, BFS, 해시맵, 구현
정답자
아직 제출이 없습니다

문제

Carlinhos loves movies, and recently he has been fascinated by the Bacon Number, which is defined as follows.

  • The Bacon number of the actor Kevin Bacon is equal to 00;
  • If the smallest Bacon number of an actor with whom XX has appeared in the same movie is bb, the bacon number of the actor XX is b+1b + 1.

That is, the Bacon number measures the shortest path between any actor and the actor Kevin Bacon, in which two actors are connected if they appeared together in the same movie.

Carlinhos is interested in a more general problem: given two actors, how to connect them through intermediate movies and actors? Given NN movies, and, for each movie, which of the existing MM actors acted in it. Carlinhos wants to answer QQ queries: in the ii-th of them, we want to compute some way to connect actor x_ix\_i with actor y_iy\_i. We must find some sequence x_i=a_1,f_1,a_2,f_2,…,f_k−1,a_k=y_ix\_i = a\_1, f\_1, a\_2, f\_2, \dots , f\_{k-1}, a\_k = y\_i, where 1≤a_j≤N1 ≤ a\_j ≤ N are actors and 1≤f_j≤M1 ≤ f\_j ≤ M are movies, and actor a_ja\_j acted in movies f_j−1f\_{j-1} and f_jf\_j, or indicate that no such sequence exists.

입력

In the first line of the input, two integers NN (1≤N≤1001 ≤ N ≤ 100) and MM (1≤M≤1061 ≤ M ≤ 10^6) are given, the number of movies and the number of actors.

NN lines follow. In the ii-th line, the first integer n_in\_i (1≤n_i≤M1 ≤ n\_i ≤ M) denotes the number of actors in movie ii. Next, n_in\_i numbers in ascending order separated by spaces: the indices, from 11 to MM, of the actors who acted in movie ii.

The next line, contains an integer QQ (1≤Q≤1041 ≤ Q ≤ 10^4): the number of queries.

The next QQ lines describe the queries. In the ii-th of them, read two numbers x_ix\_i, y_iy\_i (1≤x_i≠y_i≤M1 ≤ x\_i \ne y\_i ≤ M), the actors we want to connect. It is guaranteed that the total number of actors in the movies is at most 10610^6. That is, ∑_in_i≤106\sum\_{i}{n\_i} ≤ 10^6.

출력

For each of the queries, if there is no sequence, print a line with -1. Otherwise, print two lines. In the first line, print the number of actors k_ik\_i (2≤k_i≤1062 ≤ k\_i ≤ 10^6) in some way to connect x_ix\_i and y_iy\_i. In the second, print the sequence as described, with k_ik\_i actors and k_i−1k\_i - 1 movies, alternating. If there is more than one way to connect the actors, print any of them.

예제1

  1. 예제 1

    입력
    4 6
    3 1 2 5
    3 1 3 5
    2 2 4
    1 6
    4
    1 5
    1 4
    3 4
    1 6
    
    예상 출력
    2
    1 1 5
    3
    1 1 2 3 4
    4
    3 2 1 1 2 3 4
    -1