#include <iostream>
#include <algorithm>

using namespace std;

int main()
{
	int n, a[101][101], s, t, u;
	
	while(cin >> n){
		fill(&a[0][0], &a[n][n], 99999);
		
		for(int i = 0; i <= n; i++){
			a[i][i] = 1;
		}
		for(int i = 0; i < n; i++){
			cin >> s >> t;
			while(t--){
				cin >> u;
				a[s][u] = 1;
			}
		}
		
		for(int k = 1; k <= n; k++){
			for(int i = 1; i <= n; i++){
				for(int j = 1; j <= n; j++){
					a[i][j] = (a[i][j] > a[i][k]+a[k][j])? a[i][k]+a[k][j] : a[i][j];
				}
			}
		}
		
		for(int i = 1; i <= n; i++){
			for(int j = 1; j <= n; j++){
				cout << a[i][j] << " ";
			}
			cout << endl;
		}
		
		cin >> n;
		while(n--){
			cin >> s >> t >> u;
			if(a[s][t]+1 <= u){
				cout << a[s][t]+1 << endl;
			} else {
				cout << "NA" << endl;
			}
		}
	}
	
	return 0;
}