The Longest Common Subsequence Discussions | Algorithms | HackerRank
  • + 0 comments

    include

    include

    include

    using namespace std;

    vector longestCommonSubsequence(vector& A, vector& B) { int m = A.size(); int n = B.size();

    // Initialize the DP table
    vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));
    
    // Fill the DP table
    for (int i = 1; i <= m; ++i) {
        for (int j = 1; j <= n; ++j) {
            if (A[i - 1] == B[j - 1]) {
                dp[i][j] = dp[i - 1][j - 1] + 1;
            } else {
                dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);
            }
        }
    }
    
    // Reconstruct the longest common subsequence
    vector<int> lcs;
    int i = m, j = n;
    while (i > 0 && j > 0) {
        if (A[i - 1] == B[j - 1]) {
            lcs.push_back(A[i - 1]);
            i--;
            j--;
        } else if (dp[i - 1][j] > dp[i][j - 1]) {
            i--;
        } else {
            j--;
        }
    }
    
    reverse(lcs.begin(), lcs.end());
    return lcs;
    

    }

    int main() { int m, n; cin >> m >> n;

    vector<int> A(m);
    vector<int> B(n);
    
    for (int i = 0; i < m; ++i) {
        cin >> A[i];
    }
    
    for (int i = 0; i < n; ++i) {
        cin >> B[i];
    }
    
    vector<int> result = longestCommonSubsequence(A, B);
    
    // Print the longest common subsequence
    for (int i = 0; i < result.size(); ++i) {
        cout << result[i] << " ";
    }
    cout << endl;
    
    return 0;
    

    }