ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • [๋ฐฑ์ค€] 19941 ํ–„๋ฒ„๊ฑฐ ๋ถ„๋ฐฐ with Python
    PS 2022. 2. 20. 23:12
    728x90
    ๋ฐ˜์‘ํ˜•

    ๐Ÿ“Œ BOJ 19941 ํ–„๋ฒ„๊ฑฐ ๋ถ„๋ฐฐ

    ๐Ÿ’ก ์กฐ๊ฑด

    1. ์‹ํƒ์˜ ๊ธธ์ด๊ฐ€ N์ด๋‹ค.
      ์‚ฌ๋žŒ๋“ค(P)์€ ์ž์‹ ์˜ ์œ„์น˜์—์„œ ๊ฑฐ๋ฆฌ๊ฐ€ K ์ดํ•˜์ธ ํ–„๋ฒ„๊ฑฐ๋ฅผ ๋จน์„ ์ˆ˜ ์žˆ๋‹ค.
      1 <= N <= 20,000
      1 <= K <= 10
    2. ํ–„๋ฒ„๊ฑฐ๋ฅผ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ์‚ฌ๋žŒ์˜ ์ตœ๋Œ€ ์ˆ˜๋ฅผ ๊ตฌํ•˜๋Š” ํ”„๋กœ๊ทธ๋žจ์„ ์ž‘์„ฑ.
    3. ๊ทธ๋ฆฌ๋”” ์•Œ๊ณ ๋ฆฌ์ฆ˜ ์œ ํ˜•์˜ ๋ฌธ์ œ

    ๐Ÿ–ฅ ์†Œ์Šค ์ฝ”๋“œ

    from sys import stdin
    
    n, k = map(int, stdin.readline().split())
    arr = list(stdin.readline().rstrip())
    res = 0
    
    for i in range(n):
        if arr[i] == 'P':
            for j in range(i - k, i + k + 1):
                if -1 < j < n:
                    if arr[j] == 'H':
                        arr[j] = '-'
                        res += 1
                        break
    
    print(res)

    ๐Ÿ”– ์˜ˆ์ œ ๋ฐ ์‹คํ–‰๊ฒฐ๊ณผ

    ์˜ˆ์ œ

    20 1
    HHPHPPHHPPHPPPHPHPHP

    ์‹คํ–‰๊ฒฐ๊ณผ

    8

    โŒจ๏ธ ๋ฌธ์ œ ํ’€์ด

    1. ์‹ํƒ์˜ ๊ธธ์ด N๊ณผ ํ–„๋ฒ„๊ฑฐ๋ฅผ ๋จน์„ ์ˆ˜ ์žˆ๋Š” ๊ฑฐ๋ฆฌ K ๋ฅผ ์ž…๋ ฅ๋ฐ›๋Š”๋‹ค.
    2. N ๊ธธ์ด์˜ ํ–„๋ฒ„๊ฑฐ์™€ ์‚ฌ๋žŒ์˜ ์œ„์น˜์˜ ์ •๋ณด๊ฐ€ ๋‹ด๊ธด ๋ฌธ์ž์—ด์„ ์ž…๋ ฅ๋ฐ›์•„ arr ๋ฆฌ์ŠคํŠธ์— ์ €์žฅํ•œ๋‹ค.
    3. n ๋งŒํผ arr ๋ฆฌ์ŠคํŠธ๋ฅผ ์ˆœํšŒํ•˜๋ฉด์„œ arr[i]๊ฐ€ ์‚ฌ๋žŒ์ผ ๋•Œ, i - k ๋ถ€ํ„ฐ i + k + 1 ๊นŒ์ง€ ์ˆœํšŒํ•œ๋‹ค
      i๋ฒˆ์งธ์— ์œ„์น˜ํ•œ ์‚ฌ๋žŒ์ด i - k ๋ถ€ํ„ฐ i + k + 1 ๊ฑฐ๋ฆฌ์˜ ํ–„๋ฒ„๊ฑฐ๋ฅผ ๋จน์„ ์ˆ˜ ์žˆ๊ธฐ ๋•Œ๋ฌธ์—.
    4. 0 <= j < n ์˜ ์กฐ๊ฑด์„ ๋งŒ์กฑํ•˜๊ณ  arr[j]๊ฐ€ ํ–„๋ฒ„๊ฑฐ๋ผ๋ฉด arr์˜ ํ•ด๋‹น ๋ฒˆํ˜ธ๋ฅผ ์ด๋ฏธ ๋จน์€ ํ‘œ์‹œ๋กœ - ๋กœ ๋ณ€๊ฒฝํ•˜๊ณ  res + 1, break

    ๐Ÿ’พ ๋Š๋‚€์ 

    1. ๊ทธ๋ฆฌ๋””๋Š” ๊ฐœ๋…์ž์ฒด๋กœ๋Š” ์ดํ•ด๊ฐ€ ์‰ฌ์šฐ๋‚˜ ๋ง‰์ƒ ๋ฌธ์ œ๋ฅผ ํ’€๋ฉด ๋จธ๋ฆฌ์•ˆ์—์„œ ๊ผฌ์—ฌ๋ฒ„๋ฆฌ๋Š” ๊ฒฝ์šฐ๊ฐ€ ๋งŽ๋‹ค.
    2. ์•ž์œผ๋กœ ๊ทธ๋ฆฌ๋””๋ฅผ ํ’€ ๋•Œ๋Š” ๋งˆ์Œ์„ ๋‚ด๋ ค๋†“๊ณ  ์ฒœ์ฒœํžˆ ์ƒ๊ฐํ•ด๋ณด๋Š” ์Šต๊ด€์„ ๊ธธ๋Ÿฌ์•ผ๊ฒ ๋‹ค
    ๋ฐ˜์‘ํ˜•

    ๋Œ“๊ธ€

Designed by Tistory.