백준 9375 자바

손찬호·2024년 6월 22일
0

알고리즘

목록 보기
68/91

https://www.acmicpc.net/problem/9375

풀이 아이디어

hashMap, 조합 경우의 수

해시맵을 이용해 옷 종류별로 카운트를 세며 저장한다.
hashClothes.merge(type, 1, Integer::sum);
각 종류별 조합(Combination)의 경우의 수를 구한다. 이때 공집합은 제외하므로 -1을 해준다.
옷 종류가 0이면 0을 출력하고 다음 테스트 케이스로 넘어간다.

새로 배운 내용

주로 해시맵에 저장하고 특정 key의 value만 가져오는 방식으로만 사용했는데
해시맵에 더 다양한 기능을 사용하는 방법을 배우게 되었다.

해시맵 키 중복되는 경우 카운트 +1

해쉬맵에 같은 키값이 없으면 추가하고, 있으면 +1 더하는 메서드를
어떻게 구현하면 좋을까 고민했는데 merge함수를 사용해서
해시맵에 key가 없으면 value=1로 추가하고
key가 있으면 value+1를 수행한다.

HashMap<String, Integer> hashClothes = new HashMap<>();
...
// 해당 키값이 없으면 value 1로 추가, 있으면 해당 키의 값을 1증가
hashClothes.merge(type, 1, Integer::sum); 

해시맵 모든 값을 리스트로 받기

해시맵에 저장한 함수를 values()함수를 사용해서 Collection<Integer>형태로 가져오고
new ArrayList<>(hashClothes.values())형태로 ArrayList로 선언할 수 있다.

HashMap<String, Integer> hashClothes = new HashMap<>();
...
// 해시맵의 모든 값을 리스트로 반환
ArrayList<Integer> values = new ArrayList<>(hashClothes.values());

풀이 코드

import java.util.*;
import java.io.*;
public class _9375 {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int t = Integer.parseInt(br.readLine()); // 테스트 케이스 개수
        StringTokenizer st;
        for(int i=0;i<t;i++){
            // 옷 종류별로 카운트 계산
            HashMap<String, Integer> hashClothes = new HashMap<>();
            int n = Integer.parseInt(br.readLine()); // 가진 옷 종류

            // 옷이 없는 경우
            if(n==0){
                System.out.println(0);
                continue;
            }

            for(int j=0;j<n;j++){
                st = new StringTokenizer(br.readLine());
                st.nextToken(); // 옷 이름은 생략
                String type = st.nextToken();
                // 해당 키값이 없으면 value 1로 추가, 있으면 해당 키의 값을 1증가
                hashClothes.merge(type, 1, Integer::sum); 
            }
            // 해시맵의 모든 값을 리스트로 반환
            ArrayList<Integer> values = new ArrayList<>(hashClothes.values());
            // System.out.println(values.toString());
            long allCase = 1;
            for(Integer value: values){
                // allCase *= Math.pow(2, value);
                allCase *= value+1; // 입고 안 입고
            }
            allCase--; // 모두 안 입는 경우의 수 제외

            System.out.println(allCase);
        }
    }
}
profile
매일 1%씩 성장하려는 주니어 개발자입니다.

0개의 댓글

관련 채용 정보