简体   繁体   中英

Longest Common Subsequence is not showing the result

I have written this code using dynamic programming approach and I think the logic is good but the code is not displaying the result. The code is as follows:

#include <iostream>
using namespace std;

void LCS(int input1[], int input2[], int n, int m) {
    int L[n + 1][m + 1];  /*This matrix stores the length of common subsequences*/
    for (int i = 0; i <= n; i++) {
        for (int j = 0; j <= m; j++) {
            if (i == 0 || j == 0)
                L[i][j] = 0;
            else if (input1[i - 1] == input2[j - 1]) 
                L[i][j] = 1 + L[i - 1][j - 1]; 
            else
                L[i][j] = max(L[i - 1][j], L[i][j - 1]);
        }
    }
    int index = L[n][m];
    int lcs[index];
    int i = n, j = m;
    while (i > 0 && j > 0) {
        if (input1[i - 1] == input2[j - 1]) {
            lcs[index - 1] = input1[i - 1];
            i--;
            j--;
            index--;
        } else if (L[i - 1][j] > L[i][j - 1])
            i--;
        else
            j--;

    }
    for (int i = 0; i < index; i++){
        cout << lcs[i];
    }

}
int main() {
    int n, m;
    cin >> n >> m;
    int input1[n], input2[m]; /*two arrays from which longest subsequnce is to be found*/
    for (int i = 0; i < n; i++)
        cin >> input1[i];
    for (int i = 0; i < m; i++)
        cin >> input2[i];
    LCS(input1, input2, n, m);
    return 0;
}

The code terminates without showing any result!

I even switched to a different IDE but its the same. What is wrong with this?

You are modifying the index variable. Create a copy of it and modify that. Here I used temp .

int index = L[n][m];
int temp = index;
int lcs[index];
int i = n, j = m;
while (i > 0 && j > 0) {
    if (input1[i - 1] == input2[j - 1]) {
        lcs[temp - 1] = input1[i - 1];
        i--;
        j--;
        temp--;
    } else if (L[i - 1][j] > L[i][j - 1])
        i--;
    else
        j--;

}
for (int i = 0; i < index; i++){
    cout << lcs[i];
}

In your version index is decremented to zero when you want to print the result so nothing will be printed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM