백준 I’ve Been Everywhere, Man

KIMYEONGJUN·2026년 2월 1일
post-thumbnail

문제

내가 생각했을때 문제에서 원하는부분

The first line of input contains a single positive integer T ≤ 50 indicating the number of test cases.
The first line of each test case also contains a single positive integer n indicating the number of work trips Alice has taken so far.
The following n lines describe these trips.
The ith such line simply contains the name of the city Alice visited on her ith trip.
Alice’s work only sends her to cities with simple names: city names only contain lowercase letters, have at least one letter, and do not contain spaces.
The number of trips is at most 100 and no city name contains more than 20 characters.

For each test case, simply output a single line containing a single integer that is the number of distinct cities that Alice has visited on her work trips.

내가 이 문제를 보고 생각해본 부분

BufferedReader를 사용해 입력을 빠르게 읽는다.
첫 줄에 테스트 케이스 수 T를 읽는다.
각 테스트 케이스마다 n번만큼 도시 이름을 한 줄씩 읽는다.
HashSet<String>을 생성해서, 각 도시 이름을 넣으면 중복된 도시는 자동으로 걸러진다.
cities.size()를 출력하면 방문한 서로 다른 도시의 수가 된다.
반복문이 끝나면 br.close()로 자원을 닫는다.

코드로 구현

package baekjoon.baekjoon_32;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashSet;
import java.util.Set;


// 백준 11645번 문제
public class Main1285 {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

        int T = Integer.parseInt(br.readLine());  // 테스트 케이스 수

        for (int t = 0; t < T; t++) {
            int n = Integer.parseInt(br.readLine());  // 출장 횟수
            Set<String> cities = new HashSet<>();

            for (int i = 0; i < n; i++) {
                String city = br.readLine();
                cities.add(city);  // Set에 넣어 중복 자동 제거
            }

            System.out.println(cities.size());  // 서로 다른 도시 갯수 출력
        }

        br.close();
    }
}

마무리

코드와 설명이 부족할수 있습니다. 코드를 보시고 문제가 있거나 코드 개선이 필요한 부분이 있다면 댓글로 말해주시면 감사한 마음으로 참고해 코드를 수정 하겠습니다.

profile
Junior backend developer

0개의 댓글