반응형

문제 출처 :


https://www.acmicpc.net/problem/5525



알고리즘 분석 :


문제 해결에 필요한 사항

1. KMP 알고리즘 :: http://www.crocus.co.kr/559


이문제는 전형적인 KMP 알고리즘으로 해결이 가능한 문제이다.


kmp에 대한 내용은 위 링크를 참조하면 된다.


Pn을 구하는 방법에 대해서는 다음과 같다.


우선, string에 I를 추가해두고  n의 크기에 따라 OI를 추가해주면 된다.


이때 결과적으로 만들어진 Pn 이라는 string은 KMP 알고리즘에서 찾기위해 쓰이는 문자열로 이용될 것이다.


아래 주석을 달아두었는데, 저 주석은 문자열의 몇번째 위치에서 Pn이 나타나는지 모아둔 벡터이다. 
















소스 코드 : 


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#include <iostream>
#include <string>
#include <cstdio>
#include <vector>
 
using namespace std;
 
vector<int> getPi(string p)
{
    int m = (int)p.size();
    int j = 0;
 
    vector<int> pi(m, 0);
 
    for (int i = 1; i< m; i++) {
        while (j > && p[i] != p[j])
            j = pi[j - 1];
        if (p[i] == p[j])
            pi[i] = ++j;
    }
    return pi;
}
 
vector<int> kmp(string s, string p)
{
    vector<int> ans;
    auto pi = getPi(p);
    int n = (int)s.size(), m = (int)p.size(), j = 0;
    for (int i = 0; i < n; i++) {
        while (j>&& s[i] != p[j])
            j = pi[j - 1];
        if (s[i] == p[j]) {
            if (j == m - 1) {
                ans.push_back(i - m + 1);
                j = pi[j];
            }
            else {
                j++;
            }
        }
    }
    return ans;
}
 
int main()
{
    int n;
    scanf("%d"&n);
    
    string Pn = "I";
 
    for (int i = 0; i < n; i++)
        Pn += "OI";
 
    scanf("%d"&n);
    
    string str;
    cin >> str;
 
    vector<int> matched = kmp(str, Pn);
 
    printf("%d\n", (int)matched.size());
 
    /*
    for (auto i : matched)
        printf("%d ", i + 1);
    */
    return 0;
}
 
//                                                       This source code Copyright belongs to Crocus
//                                                        If you want to see more? click here >>
Crocus


반응형

'Applied > 알고리즘 문제풀이' 카테고리의 다른 글

[3986번] 좋은 단어  (2) 2017.10.11
[7785번] 회사에 있는 사람  (0) 2017.10.10
[2688번] 줄어들지 않아  (0) 2017.10.09
[9613번] GCD 합  (0) 2017.10.09
[10473번] 인간 대포  (0) 2017.10.09