PS/BOJ

왜 안풀림

akinakamori 2022. 8. 15. 02:39
728x90
SMALL

하..

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

 

1786번: 찾기

첫째 줄에, T 중간에 P가 몇 번 나타나는지를 나타내는 음이 아닌 정수를 출력한다. 둘째 줄에는 P가 나타나는 위치를 차례대로 공백으로 구분해 출력한다. 예컨대, T의 i~i+m-1번 문자와 P의 1~m

www.acmicpc.net

 

글 읽기 - 40% 쯤에서 틀립니다 문제가 뭔지 도저히 모르겠어요...

댓글을 작성하려면 로그인해야 합니다.

www.acmicpc.net

 

 

 

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <set>
using namespace std;

void kmp(string t, string p, vector<int> &box) {
    int ans = 0;
    int i = 0, j = 0;
    set<int> pos;
    
    while (i < t.length()) {
        if (t[i] == p[j]) {
            i++;
            j++;
        } else {
            if (j == 0) {
                i++;
            } else {
                j = box[j-1];
            }
        }
        if (j == p.length()) {
            pos.insert(i - p.length() + 1);
            j = box[j-1];
            i = i - p.length() + 2;
            ans++;
        }
    }
    cout << ans << '\n';
    for (auto i : pos) {
        cout << i << " ";
    }
}

void get_index(string p, vector<int> &box) {
    int i = 0, j = 1;
    while (j < p.length()) {
        if (p[i] == p[j]) {
            box[j] = i+1;
            i++;
            j++;
        } else {
            if (i == 0) {
                j++;
            } else {
                i = box[i-1];
            }
        }
    }
}

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    
    string T, P;
    getline(cin, T);
    getline(cin, P);
    // if (T.at(T.size() - 1) == '\n') T.erase(T.end());
    vector<int> v(P.length(), 0);
    
    get_index(P, v);
    kmp(T, P, v);
    
    return 0;
}
728x90
LIST

'PS > BOJ' 카테고리의 다른 글

백준 3184 (python) 양  (3) 2022.09.01
백준 1389 (python) 케빈 베이컨의 6단계 법칙  (2) 2022.08.29
백준 1913번 (C++) 달팽이  (0) 2022.08.11
백준 2468 (C++) 안전 영역  (0) 2022.03.20
백준 14442 (C++) 벽 부수고 이동하기 2  (2) 2022.03.18