努力使最长公共子序列代码并行(C)

时间:2019-09-11 05:11:45

标签: c openmp longest-substring

当前尝试使代码查找两个给定字符串的longest common subsequence。我已经使代码按顺序工作,但是我受命进行家庭作业以实现OpenMP和OpenMPI(尚不为此担心)。我的主要目标是让我的for循环找到给定LCS的长度,以在omp创建的线程之间并行运行,但是到目前为止,我的所有尝试似乎都是错误的。

我本来以为可能不使用某些变量(例如I和K)不是私有的,但我认为由于这些变量实际上并没有被修改,所以没关系。 Ive还研究了对我的嵌套循环使用折叠和减少子句,但仍不确定如何充分利用它们。

/**
 * Find the longest subsequence. Initially counts counts the length of the
 * longest subsequence. It then uses this length to count back and find each 
 * char that is part of the LCS.
 */
char* subseq(char** strings, int size0, int size1) {

    int count[size0 + 1][size1 + 1]; //The LCS "Table"
    int i, k;

    //Count the length of the LCS
    #pragma omp parallel shared(count) private(i, k)
    {
        #pragma omp for
        for (i = 0 ; i <= size0; i++) {
            for (k = 0; k <= size1; k++) {
                if (i == 0 || k == 0) {
                    count[i][k] = 0;
                } else if (strings[0][i - 1] == strings[1][k - 1]) {
                    count[i][k] = count[i - 1][k - 1] + 1;
                } else {
                 count[i][k] = max(count[i][k - 1], count[i - 1][k]);
                }
            }
        }
    }





    int index = count[size0][size1];
    printf("count = %d\n", index);
    char * lcs = malloc((index + 1) * sizeof(char));
    lcs[index] = '\0';
    i = size0;
    k = size1;

    //Find each char in the LCS
    while (i > 0 && k > 0) {
        if (strings[0][i - 1] == strings[1][k - 1]) {
            lcs[index - 1] = strings[0][i - 1];
            i--;
            k--;
            index--;
        } else if (count[i - 1][k] > count[i][k - 1]) {
            i--;
        } else {
            k--;
        }
    }

    return lcs;
}

现在,我的两个示例字符串是“ MZJAWXU”和“ XMJYAUZ”,但是我从程序中获得的LCS长度为2而不是预期的4。哦,我没有任何错误。

没有警告或编译器错误。

0 个答案:

没有答案