Skip to content

백준 13711번 LCS 4

Published: at 오후 09:01

백준 13711번 LCS 4

문제 링크

1부터 NN까지 정수가 모두 한 번씩만 등장하기 때문에 O(NlogN)O(NlogN)에 풀 수 있다.

첫 번째 수열에서 각각의 정수가 몇 번째 인덱스에 존재하는지 기록하고, 두 번째 수열을 바탕으로 인덱스가 적혀있는 배열을 만든다. 만든 배열로 O(NlogN)O(NlogN) LIS 구하면 그게 두 수열의 LCS다.

#include <bits/stdc++.h>

using namespace std;
using ll = long long;
using ld = long double;

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

    int n;
    cin >> n;
    vector<int> v1(n), v2(n), iv(n+1), tv(n+1), lv(n+1, 1e9);
    for (auto& x : v1) {
        cin >> x;
    }
    for (auto& x : v2) {
        cin >> x;
    }

    for (int i = 0; i < n; i++) {
        iv[v1[i]] = i;
    }

    for (int i = 0; i < n; i++) {
        tv[i] = iv[v2[i]];
    }

    for (auto x : tv) {
        auto tg = lower_bound(lv.begin(), lv.end(), x);
        *tg = x;
    }

    int lis = lower_bound(lv.begin(), lv.end(), 1e9) - lv.begin();
    cout << lis;

    return 0;
}