华为OD【二元组个数】


import java.sql.Array;
import java.util.*;

public class Demo {
    public static void main(String[] args) {
        /*
input:
4
1 2 3 4
1
1
output:
1

input:
4
1 1 2 2
3
2 2 4
output:
4

intput:
4
1 1 1 1
0
1 1 1 1
output:
-1
         */
        Scanner scanner = new Scanner(System.in);
        String temp_m = scanner.nextLine();
        int m = Integer.parseInt(temp_m);
        String[] temp1 = scanner.nextLine().split(" ");
        if (temp1.length != m){
            System.out.print(-1);
            return;
        }
        HashMap<Integer,Integer> map1 = new HashMap<>();
        for (int i = 0; i < m; i++) {
            int num = Integer.parseInt(temp1[i]);
            map1.put(num,map1.getOrDefault(num,0) + 1);
        }
        String temp_n = scanner.nextLine();
        int n = Integer.parseInt(temp_n);
        String[] temp2 = scanner.nextLine().split(" ");
        if (temp2.length != n){
            System.out.print(-1);
            return;
        }
        HashMap<Integer, Integer> map2 = new HashMap<>();
        for (int i = 0; i < n; i++){
            int num = Integer.parseInt(temp2[i]);
            map2.put(num,map2.getOrDefault(num,0) + 1);
        }
        int sum = 0;
        for(Integer key : map1.keySet()){
            if(map2.containsKey(key)){
                sum += map1.get(key) * map2.get(key);
            }
        }
        System.out.print(sum);
    }
}
posted @ 2025-05-01 18:23  破忒头头  阅读(13)  评论(0)    收藏  举报