[Algorith Study] 백준 10814

11019 단어 algorithmalgorithm

문제 출처 : https://www.acmicpc.net/problem/10814

문제 접근

문제를 보자마자 dictionary를 통해 해결하면 좋을 것 같다는 아이디어가 떠올라 자바에서 제공하는 hashmap을 활용해 문제를 해결했습니다.
Dictionary는 key와 value로 구성되는 자료구조로 key을 통해 value를 호출할 수 있는 형태입니다.

소스 코드

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

public class BOJ_10814 {
    public static void main(String[] args) throws IOException{
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringTokenizer st;
        HashMap<Integer, ArrayList<String>> people = new HashMap<Integer, ArrayList<String>>();
        int N = Integer.parseInt(br.readLine());
        for(int i = 0; i < N; i++){
            st = new StringTokenizer(br.readLine());
            int age = Integer.parseInt(st.nextToken());
            String name = st.nextToken();
            if(people.keySet().contains(age)) people.get(age).add(name);
            else{
                people.put(age, new ArrayList<String>());
                people.get(age).add(name);
            }
        }
        // 키 값을 정렬하는 코드
        Object[] ages = people.keySet().toArray();
        Arrays.sort(ages);
        for(Object key : ages){
            for(int j = 0; j < people.get(key).size(); j++){
                System.out.println(key+" "+people.get(key).get(j));
            }
        }
    }
}

좋은 웹페이지 즐겨찾기