import java.util.ArrayList; import java.util.List; import java.util.Scanner; import java.util.Set; import java.util.TreeSet; // 注意类名必须为 Main, 不要有任何 package xxx 信息 public class Main { public static void main(String[] args) { Scanner in = new Scanner(System.in); // 注意 hasNext 和 hasNextLine 的区别 while (in.hasNextInt()) { // 注意 while 处理多个 case int n1 = in.nextInt(); int[]arr1 = new int[n1]; for (int i = 0; i < n1; i++) { arr1[i] = in.nextInt(); } int n2 = in.nextInt(); Set<Integer>set = new TreeSet<>(); for (int i = 0; i < n2; i++) { set.add(in.nextInt()); } //转化成list集合方便遍历 List<Integer>list = new ArrayList<>(set); //用于记录次数 List<Integer>counts = new ArrayList<>(); //用于记录元素下标和元素 List<Integer>datas = new ArrayList<>(); for (int i = 0; i < list.size(); i++) { String s2 = list.get(i) + ""; int count = 0; for (int j = 0; j < arr1.length; j++) { String s1 = arr1[j] + ""; if (s1.contains(s2)) { count++; datas.add(j); datas.add(arr1[j]); } } counts.add(count ); } int sum = 0; for (Integer count : counts) { //这里要做一个大于0的判断,否则次数会出错 if(count>0) sum = sum+count*2+2 ; } System.out.print(sum + " "); int j = 0; for (int i = 0; i < counts.size(); i++) { //这道题的难点在于输入输出,分段遍历集合时上限是每次遍历长度的累加值,否则就会遍历不到数据 int len =j+counts.get(i)*2; if (counts.get(i) > 0) { System.out.print(list.get(i) + " "); System.out.print(counts.get(i) + " "); for (; j < len; j++) { System.out.print(datas.get(j) + " "); } } } } } }