跳到正文

剪贴板

剪贴板 0o2wamv1

原文
剪贴板信息

剪贴板信息

收录
更新

P2138 题解 C++

C++
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

const int MAXN = 300;

string a, b;
size_t asize, bsize;

int f[MAXN][MAXN];

int get_ans();

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);

    cin >> a >> b;
    asize = a.size();
    bsize = b.size();

    if (asize < bsize) {
        swap(asize, bsize);
        swap(a, b);
    }

    if (a == b) {
        cout << 1 << endl;
        return 0;
    }

    cout << get_ans() << endl;

    return 0;
}

int get_ans() {
    for (int i = 1; i <= asize; i++) {
        for (int j = 1; j <= bsize; j++) {
            if (a[i - 1] == b[j - 1]) {
                f[i][j] = f[i - 1][j - 1] + 1;
            } else {
                f[i][j] = max(f[i - 1][j], f[i][j - 1]);
            }
        }
    }

    int lcs = f[asize][bsize];
    int ans = 0;
    while (lcs * 2 < asize) {
        ans++;
        lcs += bsize;
        bsize += bsize;
    }
    ans++;
    return ans;
}