PS

BOJ 27485 : Compress Words

lickelon 2024. 11. 3. 16:08

코드

#include <bits/stdc++.h>

#define all(x) (x).begin(), (x).end()

#define INF 0x7FFFFFFF

using namespace std;

using ll = long long;
using ld = long double;
using pii = pair<int,int>;
using pll = pair<ll, ll>;

vector<int> getPi(string P) {
    int L = (int)P.size();
    vector<int> Pi(L,0);
    int j = 0;
    for(int i = 1; i < L; ++i) {
        while(j > 0 && P[i] != P[j])
            j = Pi[j-1];
        if(P[i] == P[j])
            Pi[i] = ++j;
    }
    return Pi;
}

int main()
{
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);

    int n;
    cin >> n;
    string ans;
    cin >> ans;
    for(int i = 1; i < n; i++) {
        string s;
        cin >> s;
        int l = min(s.length(), ans.length());
        string t = s.substr(0, l) + "~" + ans.substr(ans.length()-l);
        auto Pi = getPi(t);
        ans += s.substr(min(l, Pi.back()));
    }
    cout << ans;

    return 0;
}

풀이

합쳐야 할 앞 문자열을 A, 뒷 문자열을 B라고 하자.

L = min(A의 길이, B의 길이)라고 할 때, 새로운 문자열 S = B의 뒤에서부터 L개 문자 + 구분자 + A의 앞에서부터 L개 문자 를 만든다.

S의 실패함수를 구한다.

중복되는 문자열은 min(L, 실패함수의 마지막 값)이다.

728x90