【问题标题】:Longest Common Subsequence is not showing the result最长公共子序列未显示结果
【发布时间】:2016-09-27 17:18:02
【问题描述】:

我使用动态编程方法编写了这段代码,我认为逻辑很好,但代码没有显示结果。代码如下:

#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,但它是相同的。这有什么问题?

【问题讨论】:

  • 调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
  • 您还可以添加 printf 语句来检查您的矩阵 L 在前两个循环后是否正确。
  • 我也看不出这与dynamic-programming有什么关系
  • 检查你的索引变量,如果你的程序终止了,“没有显示任何结果”可能会导致你的最后一个循环不起作用
  • @πάνταῥεῖ 这是一个经典的 dp 问题。 en.wikipedia.org/wiki/…

标签: c++ algorithm dynamic-programming


【解决方案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 会递减为零,因此不会打印任何内容。

【讨论】:

    猜你喜欢
    • 2011-03-01
    • 2023-04-02
    • 1970-01-01
    • 2011-02-25
    • 2013-02-13
    • 1970-01-01
    • 1970-01-01
    • 2012-08-29
    相关资源
    最近更新 更多