본문 바로가기
Problem Solving/Baekjoon

[백준] 9728 Pair Sum - Data Structure / Java

by graycode 2023. 11. 1.

 문제 링크

 

9728번: Pair Sum

You are given an integer array of size N and an integer M. This array has (N*(N-1))/2 different pairs. You need to calculate how many of those pairs have the sum equal to M. For example, if the array is {1,2,3,4} and M is 5, then there are exactly 2 pairs

www.acmicpc.net

 

 풀이 코드

import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.HashSet;
import java.util.Set;

public class Main {

    public static void main(String[] args) throws IOException {
        BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(System.out));
        StringBuilder sb = new StringBuilder();

        Set<Integer> set = new HashSet<>();

        int t = read();
        for (int tc = 1; tc <= t; tc++) {
            int n = read(), m = read();

            int[] arr = new int[n];
            while (n-- > 0) set.add(m - (arr[n] = read()));

            int cnt = 0;
            for (int i : arr) if (set.contains(i)) cnt++;

            sb.append("Case #").append(tc).append(": ").append(cnt / 2).append("\n");
            set.clear();
        }

        bw.write(sb.toString());
        bw.flush();
    }

    private static int read() throws IOException {
        int c, n = System.in.read() & 15;
        while ((c = System.in.read()) > 32) n = (n << 3) + (n << 1) + (c & 15);

        return n;
    }

}

댓글