๊ธฐ๋ก๋ฐฉ

BOJ_4158 : CD ๋ณธ๋ฌธ

CodingTest/Java

BOJ_4158 : CD

Soom_1n 2022. 12. 1. 16:51

๐Ÿ‘‰ ๋ฌธ์ œ๋งํฌ

 

4158๋ฒˆ: CD

์ž…๋ ฅ์€ ์—ฌ๋Ÿฌ ๊ฐœ์˜ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค๋กœ ์ด๋ฃจ์–ด์ ธ ์žˆ๋‹ค. ๊ฐ ํ…Œ์ŠคํŠธ ์ผ€์ด์Šค์˜ ์ฒซ์งธ ์ค„์—๋Š” ์ƒ๊ทผ์ด๊ฐ€ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” CD์˜ ์ˆ˜ N, ์„ ์˜์ด๊ฐ€ ๊ฐ€์ง€๊ณ  ์žˆ๋Š” CD์˜ ์ˆ˜ M์ด ์ฃผ์–ด์ง„๋‹ค. N๊ณผ M์€ ์ตœ๋Œ€ ๋ฐฑ๋งŒ์ด๋‹ค. ๋‹ค์Œ ์ค„

www.acmicpc.net



๐Ÿ”ธ ๋ฌธ์ œ ๋ถ„์„ ๐Ÿ”ธ

  • n๊ณผ m์ด ์ž…๋ ฅ๋˜๋ฉด n๊ฐœ์˜ ์ˆ˜์™€ m๊ฐœ์˜ ์ˆ˜๊ฐ€ ์ž…๋ ฅ๋˜๊ณ  ๊ฒน์น˜๋Š” ์ˆซ์ž์˜ ๊ฐœ์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค.
    • ์˜ค๋ฆ„์ฐจ์ˆœ ์ •๋ ฌ๋œ ์ˆ˜๊ฐ€ ์ž…๋ ฅ๋˜๋ฏ€๋กœ ํˆฌ ํฌ์ธํ„ฐ ์•Œ๊ณ ๋ฆฌ์ฆ˜์„ ์‚ฌ์šฉํ•ด ํ’€์ดํ•œ๋‹ค.
  • 0 0์ด ์ž…๋ ฅ ๋  ๋•Œ๊นŒ์ง€ ๋ฐ˜๋ณตํ•œ๋‹ค.

๐Ÿ”ธ ์ฝ”๋“œ ๐Ÿ”ธ

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

public class Main {
    public static void main(String[] args) throws IOException {
        BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
        while (true) {
            StringTokenizer st = new StringTokenizer(br.readLine());
            int n = Integer.parseInt(st.nextToken());
            int m = Integer.parseInt(st.nextToken());
            if (n == 0 && m == 0)
                break;

            int[] arr_n = new int[n];
            int[] arr_m = new int[m];
            for (int i = 0; i < n; i++) {
                arr_n[i] = Integer.parseInt(br.readLine());
            }
            for (int i = 0; i < m; i++) {
                arr_m[i] = Integer.parseInt(br.readLine());
            }

            int count_n = 0, count_m = 0, answer = 0;
            while (count_n < n && count_m < m) {
                if (arr_n[count_n] > arr_m[count_m])
                    count_m++;
                else if (arr_n[count_n] < arr_m[count_m])
                    count_n++;
                else {
                    answer++;
                    count_m++;
                    count_n++;
                }
            }
            System.out.println(answer);
        }
    }
}

๐Ÿ”ธ ์ฝ”๋“œ ํ•ด์„ ๐Ÿ”ธ

  • arr_n, arr_m ๋‘ ๋ฐฐ์—ด์„ ์ˆœํšŒํ•˜๋ฉฐ ๋‹ค์Œ๊ณผ ๊ฐ™์€ ๊ทœ์น™์œผ๋กœ ์ธ๋ฑ์Šค๋ฅผ ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.
    • ๋‘ ๋ฐฐ์—ด์—ด์˜ ๊ฐ’์ด ๊ฐ™์œผ๋ฉด, ์ •๋‹ต์„ +1ํ•˜๊ณ  ๋‘ ์ธ๋ฑ์Šค๊ฐ’๋„ 1 ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.
    • ๋‘ ๋ฐฐ์—ด์˜ ๊ฐ’์ด ๋‹ค๋ฅด๋ฉด, ๊ฐ’์ด ์ž‘์€ ์ชฝ์˜ ์ธ๋ฑ์Šค๋ฅผ 1 ์ฆ๊ฐ€์‹œํ‚จ๋‹ค.

๐Ÿ”ธ end ๐Ÿ”ธ

  • ์ฒ˜์Œ์—๋Š” ํ•˜๋‚˜์˜ ๋ฐฐ์—ด๋กœ ์ฒดํฌํ•˜๊ฑฐ๋‚˜ ๋น„ํŠธ๋งˆ์Šคํ‚น์œผ๋กœ ์ฒดํฌํ•ด์•ผ ํ–ˆ๋Š”๋ฐ ๊ฐ’์ด ๋„ˆ๋ฌด ์ปค์„œ ์–ด๋ ค์› ๋‹ค.
  • ํˆฌ ํฌ์ธํ„ฐ๊ฐ€ ๋„ˆ๋ฌด ์ตœ์ ์˜ ๋ฐฉ๋ฒ•์ธ ๊ฒƒ ๊ฐ™์•„ ์„ ํƒํ–ˆ๋Š”๋ฐ, ํ•ด์‹œ ๋งต์ด๋‚˜ ์ด๋ถ„ ํƒ์ƒ‰์œผ๋กœ๋„ ํ’€์ด๊ฐ€ ๋˜๋Š” ๊ฒƒ ๊ฐ™๋‹ค.

728x90

'CodingTest > Java' ์นดํ…Œ๊ณ ๋ฆฌ์˜ ๋‹ค๋ฅธ ๊ธ€

BOJ_24389 : 2์˜ ๋ณด์ˆ˜  (0) 2022.12.05
BOJ_3595 : ๋งฅ์ฃผ ๋ƒ‰์žฅ๊ณ   (0) 2022.12.05
BOJ_3447 : ๋ฒ„๊ทธ์™•  (0) 2022.12.01
BOJ_2520 : ํŒฌ์ผ€์ดํฌ ์‚ฌ๋ž‘  (0) 2022.12.01
BOJ_2193 : ์ด์นœ์ˆ˜  (0) 2022.11.29