藍橋杯-算法訓練-審美課(Java)

對完全相反的審美進行異或操作的話就會得到全1,所以把每個人的審美存成二進制數字。把審美數據存到map裏面,這樣只需要一次遍歷就可以得到答案了。

import java.util.*;

public class Main {
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String[] firstLine = scanner.nextLine().split(" ");
        int rows = Integer.parseInt(firstLine[0]);
        int cols = Integer.parseInt(firstLine[1]);

        HashMap<Integer, Integer> map = new HashMap<>();
        for(int i = 0; i < rows; i++){
            String line = scanner.nextLine().replaceAll(" ", "");
            int score = Integer.parseInt(line, 2);
            if(map.containsKey(score)){
                map.put(score, map.get(score) + 1);
            } else{
                map.put(score, 1);
            }
        }
        scanner.close();

        int ans = 0;
        int allOnes = (int) (Math.pow(2, cols) - 1);
        for(Iterator<Integer> iterator = map.keySet().iterator(); iterator.hasNext();){
            int key = iterator.next();
            int reverse = allOnes - key;
            if(map.containsKey(reverse)){
                ans += map.get(reverse) * map.get(key);
            }
        }

        System.out.println(ans / 2);
    }

}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章