2016-09-27 42 views
-2

我已經使用動態規劃方法編寫了此代碼,我認爲邏輯很好,但代碼不顯示結果。的代碼如下:最長公共子序列未顯示結果

#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; 
} 

代碼終止而不顯示任何結果!

我甚至切換到不同的IDE,但它是相同的。這有什麼問題?

+2

解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –

+1

您還可以添加printf語句來檢查兩個第一個循環後矩陣L是否正確。 – Renaud

+0

此外,我不能發現這是如何與[標籤:動態編程] –

回答

1

您正在修改index變量。創建它的一個副本並修改它。這裏我使用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]; 
} 

在你index版本遞減到零。