To solve this problem, we need to find the longest common increasing subsequence between two given integer sequences. This can be done using a combination of dynamic programming and longest increasing subsequence (LIS) strategy with a slight modification to identify common elements.
Here's how you can implement the solution in C++:
#include <iostream>
#include <vector>
#include <algorithm>
#include <map>
using namespace std;
// Function to compute the longest increasing subsequence of common elements
void findLCIS(vector<int>& seq1, vector<int>& seq2) {
int n = seq1.size();
int m = seq2.size();
// dp array to store length of LCIS ending with seq2[j]
vector<int> dp(m + 1, 0);
// parent array to reconstruct the subsequence
vector<int> parent(m, -1);
for (int i = 0; i < n; ++i) {
int current_max = 0;
int last_index = -1;
for (int j = 0; j < m; ++j) {
if (seq1[i] == seq2[j]) {
if (dp[j] < current_max + 1) {
dp[j] = current_max + 1;
parent[j] = last_index; // link to previous index
}
}
if (seq1[i] > seq2[j]) {
if (dp[j] > current_max) {
current_max = dp[j];
last_index = j;
}
}
}
}
// Find the index of the maximum value in dp array
int length_LCIS = *max_element(dp.begin(), dp.end());
cout << length_LCIS << endl;
// Reconstruct the LCIS using the parent array
int index = max_element(dp.begin(), dp.end()) - dp.begin();
vector<int> lcis;
while (index != -1) {
lcis.push_back(seq2[index]);
index = parent[index];
}
// LCIS is built in reverse order, reverse it
reverse(lcis.begin(), lcis.end());
for (int num : lcis) {
cout << num << " ";
}
cout << endl;
}
int main() {
int M1, M2;
// Input for the first sequence
cin >> M1;
vector<int> seq1(M1);
for (int i = 0; i < M1; ++i) {
cin >> seq1[i];
}
// Input for the second sequence
cin >> M2;
vector<int> seq2(M2);
for (int i = 0; i < M2; ++i) {
cin >> seq2[i];
}
// Find the LCIS
findLCIS(seq1, seq2);
return 0;
}
Explanation:
-
Data Structures:
- We use a
dp array where dp[j] holds the length of the longest common increasing subsequence ending with seq2[j].
- A
parent array tracks the predecessors for reconstructing the subsequence.
-
Core Logic:
- For each element in
seq1, we iterate over seq2. If we find the same element, it can potentially extend an existing increasing subsequence.
- If
seq1[i] == seq2[j], we update dp[j] to current_max + 1.
- If sequences are compatible for an increase (
seq1[i] > seq2[j]), we update current_max with dp[j] to remember the longest subsequence found so far before j.
-
Reconstruction:
- After filling in the
dp array, we reconstruct the subsequence from indices using the parent array.
- The subsequence is built in reverse order, so we reverse it before printing.
This implementation computes the LCIS efficiently, adhering to the problem constraints.