๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 28432_๋๋ง์ž‡๊ธฐ

๋ฟŒ์•ผ._. 2023. 12. 26. 23:22

Silver V

๋ฌธ์ œ(์ถœ์ฒ˜: https://www.acmicpc.net/problem/28432)

< ๋๋ง์ž‡๊ธฐ >

 

๋ฌธ์ œ ํ’€์ด 

 

? ๊ฐ€ ์ฃผ์–ด์ง€๊ธฐ ์ „ ๋ฌธ์ž์—ด์˜ ๋ ๋ฌธ์ž์™€ ? ๊ฐ€ ์ฃผ์–ด์ง„ ๋’ค ๋ฌธ์ž์—ด์˜ ์ฒซ ๋ฌธ์ž๋ฅผ ์ €์žฅํ•œ ํ›„ ๋ฌธ์ž์—ด ํ›„๋ณด ์ค‘์—์„œ ์กฐ๊ฑด์— ๋งž๋Š” ๋ฌธ์ž์—ด์„ ์ฐพ๋Š”๋‹ค.

 

 my solution (Java)

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

public class _28432_ { // ๋๋ง์ž‡๊ธฐ

	public static void main(String[] args) throws IOException {
		BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));

		int n = Integer.parseInt(bf.readLine());

		Set<String> set = new HashSet<>();
		char before = '0';
		char after = '0';
		boolean flag_before = false;
		boolean flag_after = false;

		for (int i = 0; i < n; i++) {
			String str = bf.readLine();
			if (!str.equals("?")) {
				set.add(str);
				if (flag_before && !flag_after) {
					after = str.charAt(0);
					flag_after = true;
				}
			} else {
				flag_before = true;
			}
			if (!flag_before)
				before = str.charAt(str.length() - 1);

		}

		String result = "";

		int m = Integer.parseInt(bf.readLine());
		if (n == 1) {
			System.out.println(bf.readLine());
		} else {
			for (int i = 0; i < m; i++) {
				String str = bf.readLine();
				if ((str.charAt(0) == before || before == '0')
						&& (str.charAt(str.length() - 1) == after || after == '0') && !set.contains(str)) {
					result = str;
				}
			}
			System.out.println(result);
		}
	}
}
๋ณ€์ˆ˜)
n : ๋๋ง์ž‡๊ธฐ ๊ธฐ๋ก์˜ ๊ธธ์ด
set : ๋๋ง์ž‡๊ธฐ ๋‚˜์˜จ ๋ฌธ์ž์—ด
before, after : ?๊ฐ€ ์ฃผ์–ด์ง€๊ธฐ ์ „ ๋ฌธ์ž์—ด์˜ ๋ ๋ฌธ์ž,? ๊ฐ€ ์ฃผ์–ด์ง„ ํ›„ ๋ฌธ์ž์—ด์˜ ์ฒซ ๋ฌธ์ž
flag_before, flag_after : ?๊ฐ€ ์ฃผ์–ด์ง€๊ธฐ ์ „, ํ›„์˜ ์ฒดํฌ
str : ๋ฌธ์ž์—ด
result : ๋ฌธ์ œ์˜ ๋‹ต
m : ํ›„๋ณด ๋‹จ์–ด์˜ ๊ฐœ์ˆ˜

 

๋๋ง์ž‡๊ธฐ ๊ธฐ๋ก์„ ์ž…๋ ฅ ๋ฐ›๋Š”๋‹ค. ?๊ฐ€ ๋‚˜์˜ค๊ธฐ ์ „ ๋ฌธ์ž์—ด์˜ ๋ ๋ฌธ์ž์™€ ? ๊ฐ€ ๋‚˜์˜จ ํ›„์˜ ๋ฌธ์ž์—ด์˜ ์ฒซ ๋ฌธ์ž๋ฅผ ๊ฐ๊ฐ ์ €์žฅํ•œ๋‹ค. ํ›„๋ณด๋ฅผ ์ž…๋ ฅ๋ฐ›์œผ๋ฉด์„œ ๋ฌธ์ž์—ด์˜ ์ฒซ ๋ฌธ์ž์™€ ๋ ๋ฌธ์ž๊ฐ€ ์•ž์—์„œ ๊ตฌํ•œ ๋ฌธ์ž์™€ ์ผ์น˜ํ•œ๋‹ค๋ฉด ๊ทธ ๊ฐ’์„ ์ถœ๋ ฅํ•œ๋‹ค. ์ž…๋ ฅ๋ฐ›์„ ๋•Œ? ๊ฐ€ ๋งจ ์•ž๊ณผ ๋งจ ๋’ค์— ์ž…๋ ฅ๋  ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ํ›„๋ณด ๋ฌธ์ž์—ด์—์„œ ๋‹ต์„ ๊ตฌํ•  ๋•Œ ์กฐ๊ฑด์„ ์ถ”๊ฐ€ํ•œ๋‹ค.