ํ‹ฐ์Šคํ† ๋ฆฌ ๋ทฐ

728x90
๋ฐ˜์‘ํ˜•

๋ฌธ์ œ

 

1786๋ฒˆ: ์ฐพ๊ธฐ

์ฒซ์งธ ์ค„์—, T ์ค‘๊ฐ„์— P๊ฐ€ ๋ช‡ ๋ฒˆ ๋‚˜ํƒ€๋‚˜๋Š”์ง€๋ฅผ ๋‚˜ํƒ€๋‚ด๋Š” ์Œ์ด ์•„๋‹Œ ์ •์ˆ˜๋ฅผ ์ถœ๋ ฅํ•œ๋‹ค. ๋‘˜์งธ ์ค„์—๋Š” P๊ฐ€ ๋‚˜ํƒ€๋‚˜๋Š” ์œ„์น˜๋ฅผ ์ฐจ๋ก€๋Œ€๋กœ ๊ณต๋ฐฑ์œผ๋กœ ๊ตฌ๋ถ„ํ•ด ์ถœ๋ ฅํ•œ๋‹ค. ์˜ˆ์ปจ๋Œ€, T์˜ i๏ฝži+m-1๋ฒˆ ๋ฌธ์ž์™€ P์˜ 1๏ฝžm

www.acmicpc.net

 

๋ฌธ์ œ ํ’€์ด

 ๋ฌธ์ž์—ด๊ณผ ํŒจํ„ด์ด ์ฃผ์–ด์ง€๋ฉด, ์ด๋ฅผ ํ†ตํ•ด ๋ช‡ ๊ฐœ๊ฐ€ ์ผ์น˜ํ•˜๊ณ  ์–ด๋Š ์œ„์น˜์— ์ผ์น˜ํ•˜๋Š”์ง€ ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ฌธ์ œ์ด๋‹ค. ์•ž์„œ ๋‹ค๋ฃฌ 16916 ๋ถ€๋ถ„ ๋ฌธ์ž์—ด๊ณผ ๊ฐ™์ด `KMP ์•Œ๊ณ ๋ฆฌ์ฆ˜`์„ ์ดํ•ดํ•˜๊ณ  ์žˆ์œผ๋ฉด ์‰ฝ๊ฒŒ ํ•ด๊ฒฐํ•  ์ˆ˜ ์žˆ๋Š” ๋ฌธ์ œ์ด๋‹ค. ์•ž์„œ ๋‹ค๋ฃฌ ๋ฌธ์ œ์™€ ๋‹ค๋ฅธ ์ ์ด ์žˆ๋‹ค๋ฉด ํŒจํ„ด๊ณผ ์ผ์น˜ํ•˜๋Š” ๊ฒฝ์šฐ ๋ฐ”๋กœ ๊ฒฐ๊ณผ๋ฅผ ๋ฐ˜ํ™˜ํ•˜์ง€ ์•Š๊ณ , ๊ฐ’์„ ์ถ”๊ฐ€ํ•˜์—ฌ ๋ชจ๋“  ํƒ์ƒ‰์ด ๋๋‚œ ํ›„์— ๋ฐ˜ํ™˜ํ•˜๋Š” ๋ถ€๋ถ„์„ ์ˆ˜์ •ํ•˜๋ฉด ๋œ๋‹ค.

 

์ฝ”๋“œ

def make_table():
    length = len(p)
    table = [0] * len(p)
    j = 0
    for i in range(1, length):
        while j > 0 and p[i] != p[j]:
            j = table[j - 1]
        if p[i] == p[j]:
            j += 1
            table[i] = j
    return table


def kmp():
    table = make_table()
    j = 0
    ret = []
    for i in range(len(s)):
        while j > 0 and s[i] != p[j]:
            j = table[j - 1]
        if s[i] == p[j]:
            if j == len(p) - 1:
                ret.append(i - len(p) + 2)
                j = table[j]
            else:
                j += 1
    return ret


if __name__ == "__main__":
    s = input()
    p = input()
    result = kmp()
    print(len(result))
    print(*result)

 

728x90
๋ฐ˜์‘ํ˜•
๋Œ“๊ธ€
๊ธ€ ๋ณด๊ด€ํ•จ
์ตœ๊ทผ์— ์˜ฌ๋ผ์˜จ ๊ธ€
์ตœ๊ทผ์— ๋‹ฌ๋ฆฐ ๋Œ“๊ธ€