백준 오답노트/반복문

백준 - 반복문 15552번 문제 틀린 이유 + 해결 시간의 중요성

초보병일이 2022. 11. 16. 15:29
728x90

= 문제 = 

입력

첫 줄에 테스트케이스의 개수 T가 주어진다. T는 최대 1,000,000이다. 

다음 T줄에는 각각 두 정수 A와 B가 주어진다. A와 B는 1 이상, 1,000 이하이다.

출력

각 테스트케이스마다 A+B를 한 줄에 하나씩 순서대로 출력한다.

예제 입력 1

5

1 1

12 34

5 500

40 60

1000 1000

예제 출력 1

2

46

505

100

2000

 

= 처음 작성한 코드 =

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        int n = Integer.parseInt(br.readLine());
        boolean result = true;
        int count = 0;

        while(result) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            count++;
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());
            System.out.println(a + b);
            if (count == n) {
                result = false;
            }
        }
    }
}

시간을 빨리하는게 중요한 문제였다.

Scanner를 사용하는 것보다 BufferedReader를 사용하는게 시간이 더 빠르다.

 

이게 정답인 줄 알았는데 시간초과가 떴음!

 

어떻게 하면 더 빠르게 할 수 있을지 찾아봤는데

 

문제에 주어져있었다. StringBuilder를 이용해서 출력을 해야한다고.

 

= 수정한 내용 = 

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        StringBuilder sb = new StringBuilder();
        int n = Integer.parseInt(br.readLine());
        boolean result = true;
        int count = 0;

        while(result) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            count++;
            int a = Integer.parseInt(st.nextToken());
            int b = Integer.parseInt(st.nextToken());
            sb.append(a + b).append('\n');
            if (count == n) {
                result = false;
            }
        }
        System.out.println(sb);
    }
}

브론즈4 문제이지만

문제를 해결할 때, 어떤 것을 써야하는지 어떻게 하면 시간을 줄일 수 있는지 알 수 있었다.

 

아무리 쉬운 문제여도 기본적인 내용 설명과 요구 방식을 만족할 수 있는 방법을 배울 수 있으니까

 

꼭 차례대로 쉬운 문제부터 풀어보는 것이 중요하다!

728x90