#include #include #include #include #include #include using namespace std; long long used[1001][1001],n,s[151],m,t[1001][1001],qu,x,y,br; queue q; vector z[1001]; void bfs(int st) { for(int i=1; i<=n; i++) used[st][i]=-1; br=n; used[st][st]=0; br--; q.push(st); while(!q.empty()) { int x=q.front(); q.pop(); int m=z[x].size(); for(int i=0; i<=m-1; i++) { for(int j=1; j<=s[z[x][i]]; j++) { if(used[st][t[z[x][i]][j]]==-1) {q.push(t[z[x][i]][j]); used[st][t[z[x][i]][j]]=used[st][x]+1; br--; if(br==0) break;} } if(br==0) break; } if(br==0) break; } while(!q.empty()) q.pop(); } int main() { freopen("movie.in","r",stdin); freopen("movie.out","w",stdout); scanf("%lld%lld",&n,&m); for(int i=1; i<=m; i++) { scanf("%lld",&s[i]); for(int j=1; j<=s[i]; j++) { scanf("%lld",&t[i][j]); z[t[i][j]].push_back(i); } } for(int i=1; i<=n; i++) bfs(i); scanf("%lld",&qu); for(int i=1; i<=qu; i++) { scanf("%lld%lld",&x,&y); printf("%lld\n",used[y][x]); } return 0; }