[BaekJoon] ๋ฐฑ์ค€ 5525๋ฒˆ : IOIOI

Updated:

5525๋ฒˆ : IOIOI

IOI


๊ทธ๋ƒฅ ๋ฐ˜๋ณต๋ฌธ์„ ํ†ตํ•ด 1๋ถ€ํ„ฐ 1,000,000 ๊นŒ์ง€ ๋Œ๊ธฐ๋งŒ ํ•ด๋„ 2.8์ดˆ๊ฐ€ ๊ฑธ๋ฆฐ๋‹ค.

๋•Œ๋ฌธ์— O(N^2) ์ธ ์•Œ๊ณ ๋ฆฌ์ฆ˜์œผ๋กœ๋Š” ์ ˆ๋Œ€ ํ’€ ์ˆ˜ ์—†๊ณ  O(N) ๋„ index ๋ฅผ ์ „๋ถ€ ์ˆœํšŒํ•˜๋ฉด ์‹œ๊ฐ„ ์ดˆ๊ณผ๊ฐ€ ๋ฐœ์ƒํ•œ๋‹ค.

find ํ•จ์ˆ˜๋ฅผ ํ†ตํ•ด ํ’€๊ณ  ์‹ถ์—ˆ์ง€๋งŒ ์•ˆ๋  ๊ป„ ์•Œ์•„์„œ ์†๋„ ์•ˆ๋Œ€๋ณด๊ณ  ๊ทœ์น™์„ ์ฐพ๊ธฐ ์‹œ์ž‘ํ–ˆ๋‹ค.

  1. Solution1

    ๋งŒ์•ฝ IOIOIOIOI ๊ฐ€ ์ฃผ์–ด์ง€๊ณ  ์ฐพ๊ณ ์ž ํ•˜๋Š” ๋ฌธ์ž์—ด์ด IOIOI ๋ผ๋ฉด 3๊ฐœ๊ฐ€ ์กด์žฌํ•œ๋‹ค.

    IOI ํŒจํ„ด์„ ๊ณ„์† ์ฐพ์•„ ๋‚ด๊ฐ€ ์ฐพ๊ณ ์ž ํ•˜๋Š” ๋ฌธ์ž์—ด์˜ ํŒจํ„ด๊ณผ ์ผ์น˜ํ•˜๋ฉด ๊ทธ๋•Œ ๊ฐ’์„ ์˜ฌ๋ฆฐ๋‹ค.

    ๊ทธ๋ฆฌ๊ณ  ํŒจํ„ด์„ ์ฐพ์•˜๋‹ค๋ฉด index ๋Š” ๋‘ ์นธ์„ ์˜ฌ๋ฆฌ๋ฉด ๋œ๋‹ค.

    IOIOIOIOI ์—์„œ ์ฒซ ๋ฒˆ์งธ IOIOI ๋ฅผ ์ฐพ์•˜๋‹ค๋ฉด ํŒจํ„ด์€ 1์„ ๋บ€๋‹ค.

    ๊ทธ๋ž˜์•ผ ๋‹ค์Œ IOIOI ๋ฅผ ์ฐพ์„ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์ด๋‹ค.

    ํŒจํ„ด์ด ๋Š๊ธด๋‹ค๋ฉด ๋‹ค์‹œ ํŒจํ„ด์„ ์ดˆ๊ธฐํ™” ํ•œ ๋’ค index ๋ฅผ ํ•œ ์นธ๋งŒ ์˜ฌ๋ ค ๋‹ค์‹œ ๊ฒ€์‚ฌํ•˜๋ฉฐ ๋ฐ˜๋ณตํ•œ๋‹ค.


  2. Solution2

    ์‚ฌ์‹ค solution1 ํ’€์ด๋ณด๋‹ค ๋จผ์ € ์ƒ๊ฐํ–ˆ๋˜ ํ’€์ด๋Š” ์ฃผ์–ด์ง„ ๋ฌธ์ž์—ด์—์„œ ์—ฐ์†ํ•˜์ง€ ์•Š๋Š” ๋ถ€๋ถ„์„ ๋ชจ๋‘ ์ฐพ์•„๋‚ด ๋น„๊ตํ•˜๋Š” ๋ฐฉ๋ฒ•์ด์—ˆ๋‹ค.

    IIIOIOIOOOI ๊ฐ€ ์ฃผ์–ด์ง„๋‹ค๋ฉด ํŒจํ„ด์ธ IOIOIO ๋ฅผ ์ฐพ์•„๋‚ด ๋น„๊ต๋ฅผ ํ•˜๋Š” ๊ฒƒ ์ด๋‹ค.

    ๊ทธ๋Ÿฐ๋ฐ ์ด ํŒจํ„ด์„ ์ฐพ์•„๋‚ด๋Š”๊ฒŒ ๋„ˆ๋ฌด๋„ˆ๋ฌด ์ƒ๊ฐ๋ณด๋‹ค ์–ด๋ ค์› ๋‹ค..

    ๋ถ„๋ช…ํžˆ ์ •๊ทœ์‹์„ ์‚ฌ์šฉํ•˜๋ฉด ๋  ๊ฒƒ ๊ฐ™๊ธด ํ–ˆ๋Š”๋ฐ ์•„์ง ์ •๊ทœ์‹์œผ๋กœ ๋ฌธ์ž์—ด์„ ๋‹ค๋ฃจ๊ธฐ๋Š” ๋ถ€์กฑํ•œ ์‹ค๋ ฅ..

    ๋‹ค์Œ์— ๊ผญ ํ•„์š”ํ•œ ์ •๊ทœ์‹ ์ •๋„๋Š” ๊ณต๋ถ€๋ฅผ ํ•ด์•ผ๊ฒ ๋‹ค.

    ์–ด์จŒ๋“  ์—ฐ์†ํ•˜์ง€ ์•Š๋Š” ๋ถ€๋ถ„์˜ ๊ธธ์ด์—์„œ ์ฐพ๊ณ ์ž ํ•˜๋Š” ๋ฌธ์ž์—ด์˜ ๊ธธ์ด๋ฅผ ๋บ€ ๊ฐ’์„ 2 ๋กœ ๋‚˜๋ˆˆ๋’ค 1 ์„ ๋”ํ•ด์ฃผ๋ฉด ๋‹ต์ด ๋œ๋‹ค.


import sys
import re


def solution1(N, str_size, string):
	count = pattern = idx = 0

	while idx < str_size - 1:
		if string[idx - 1] == 'I' and string[idx] == 'O' and string[idx + 1] == 'I':
			pattern += 1
			if pattern == N:
				count += 1
				pattern -= 1
			idx += 1

		else:
			pattern = 0
		idx += 1

	return count


def solution2(part, sub_len):
	count = 0
	for val in part:
		if len(val) >= sub_len:
			count += (len(val) - sub_len) // 2 + 1

	return count


N = int(sys.stdin.readline().rsplit()[0])
str_size = int(sys.stdin.readline().rsplit()[0])
_string = sys.stdin.readline().rsplit()[0]

print(solution1(N, str_size, _string))

part = re.findall('I(?:OI)+', _string)
print(solution2(part, 1 + 2 * N))

Categories:

Updated:

Leave a comment