思路:开boolean的二维数组用于记录每个人有哪些物品,第一层长度为n即人数,因为人没有编号所以不用多开一个长度,而物品编号从1开始,所以第二层为m+1,有的就直接改成true,后续询问就遍历第一层,这两本书时为true就cnt++记录就OK,下面是AC代码:
import java.io.*;
import java.util.Arrays;
public class Main {
static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
static StreamTokenizer star = new StreamTokenizer(bf);
public static void main(String[] args) throws IOException{
int n = nextInt();
int m = nextInt();
boolean[][] x = new boolean[n][m+1];
for (boolean[] booleans : x) {
Arrays.fill(booleans, false);
}
for (int i = 0; i < n; i++) {
int num = nextInt();
for (int j = 0; j < num; j++) {
int u = nextInt();
x[i][u] = true;
}
}
int q = nextInt();
while (q-->0){
int a = nextInt();
int b = nextInt();
int cnt = 0;
for (boolean[] booleans : x) {
if (booleans[a] && booleans[b])
cnt++;
}
System.out.println(cnt);
}
}
static int nextInt() throws IOException{
star.nextToken();
return (int)star.nval;
}
}
感谢支持,点个关注一起学习~