๐ŸŒžAlgorithm/๐Ÿ”ฅBaekjoon

[Baekjoon] 5525_IOIOI

๋ฟŒ์•ผ._. 2023. 7. 11. 16:45

Silver I

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

< IOIOI >

 

๋ฌธ์ œ ํ’€์ด 

 

์ฒ˜์Œ์—๋Š” ๋ฌธ์ž์—ด์„ ์ „์ฒด ํƒ์ƒ‰ํ•˜๋ฉด์„œ Pn๊ณผ ์ผ์น˜ํ•˜๋Š”์ง€๋ฅผ ํ™•์ธํ–ˆ๋‹ค. ์ด ๊ณผ์ •์—์„œ ์„œ๋ธŒ ํƒœ์Šคํฌ 50์ ์„ ํš๋“ํ–ˆ๋‹ค.

 

50์  (Java)

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

public class Main {

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

		int n = Integer.parseInt(bf.readLine());
		int s = Integer.parseInt(bf.readLine());
		String str = bf.readLine();

		String x = "";
		for (int i = 0; i < n; i++) {
			x += "IO";
		}
		x += "I";

		int result = 0;

		for (int i = 0; i < s - (n * 2); i++) {
			if (str.charAt(i) == 'I') {
				String temp = str.substring(i, i + (n * 2 + 1));
				if (temp.equals(x)) {
					result += 1;
				}
			}
		}
		System.out.println(result);
	}

}

 

๋‚จ์€ 50์ ์„ ํš๋“ํ•˜๊ธฐ ์œ„ํ•ด ์‹œ๊ฐ„์„ ์ค„์—ฌ์•ผ ํ–ˆ๋‹ค.

์œ„์—์„œ๋Š” ๊ตฌํ•˜๋ ค๋Š” ๋ฌธ์ž์—ด ๊ธธ์ด๋งŒํผ ๊ณ„์†ํ•ด์„œ ๋ฌธ์ž์—ด์„ ์ž˜๋ผ์„œ ํ™•์ธํ•ด์„œ ์˜ค๋ž˜ ๊ฑธ๋ ธ๋˜ ๊ฒƒ์ด์—ˆ๋‹ค.

์ด ๋ถ€๋ถ„์„ ํ•ด๊ฒฐํ•˜๊ธฐ ์œ„ํ•ด ๋ฌธ์ž์—ด์„ ํ•œ๋ฒˆ ํƒ์ƒ‰ํ•˜๋ฉด์„œ IOI์˜ ๊ฐœ์ˆ˜๋ฅผ ๊ตฌํ•˜์—ฌ ๋‹ต์„ ๊ตฌํ–ˆ๋‹ค.

 

 

 my solution (Java)

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

public class Main {

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

		int n = Integer.parseInt(bf.readLine());
		int s = Integer.parseInt(bf.readLine());
		String str = bf.readLine();

		int cnt = 0;
		int i = 0;
		int result = 0;
		while (i < s - 2) {
			if (str.charAt(i) == 'I' && str.charAt(i + 1) == 'O' && str.charAt(i + 2) == 'I') {
				cnt += 1;
				i += 2;
			} else {
				if (cnt >= n) {
					result += cnt - n + 1;
				}
				cnt = 0;
				i += 1;
			}
		}
		if (cnt >= n)
			result += cnt - n + 1;

		System.out.println(result);
	}

}

 

Main

๋ณ€์ˆ˜)
n : Pn์˜ n
s : str์˜ ๊ธธ์ด
str : ๋ฌธ์ž์—ด
cnt : ๋ฌธ์ž์—ด์—์„œ์˜ IOI ๊ฐœ์ˆ˜
i : ๋ฌธ์ž์—ด ํƒ์ƒ‰ index
result : str์— Pn์ด ํฌํ•จ๋˜์–ด ์žˆ๋Š” ํšŸ์ˆ˜

 

- n, s, str ์ž…๋ ฅ

- ๋ฌธ์ž์—ด์„ ํƒ์ƒ‰

  1) IOI๋ผ๋ฉด cnt์ฆ๊ฐ€ ๋ฐ index +2 

  2) IOI๊ฐ€ ์•„๋‹ˆ๋ผ๋ฉด ์—ฌํƒœ IOI๊ฐ€ ๋‚˜์˜จ ํšŸ์ˆ˜(cnt)๊ฐ€ Pn๋งŒํผ ์žˆ๋‹ค๋ฉด result์— ๊ฐ’ ๋”ํ•ด์คŒ. Pn๋งŒํผ ์žˆ๋Š”์ง€ ์—†๋Š”์ง€ ์ƒ๊ด€์—†์ด cnt๋ฅผ 0์œผ๋กœ ์ดˆ๊ธฐํ™” ํ›„ index+1

- ๋ฌธ์ž์—ด ํƒ์ƒ‰ ํ›„ ๋งˆ์ง€๋ง‰์— Pn์ด ๋‚˜์™”์„ ์ˆ˜ ์žˆ์œผ๋ฏ€๋กœ ํ™•์ธ ํ›„ result์— ๊ฐ’ ๋”ํ•ด์ฃผ๊ธฐ

- result ์ถœ๋ ฅ