c - c中的openmp并行递归函数

标签 c recursion openmp permutation

我如何使用 openMP 并行化下面的递归?因为我的代码有问题可以通过这种方式解决。我从以下网站获得此代码:https://www.geeksforgeeks.org/write-a-c-program-to-print-all-permutations-of-a-given-string/

代码:

// C program to print all permutations with duplicates allowed
#include <stdio.h>
#include <string.h>

/* Function to swap values at two pointers */
void swap(char *x, char *y)
{
    char temp;
    temp = *x;
    *x = *y;
    *y = temp;
}

/* Function to print permutations of string
This function takes three parameters:
1. String
2. Starting index of the string
3. Ending index of the string. */
void permute(char *a, int l, int r)
{
   int i;
   if (l == r)
     printf("%s\n", a);
   else
   {
       for (i = l; i <= r; i++)
       {
          swap((a+l), (a+i));
          permute(a, l+1, r);
          swap((a+l), (a+i)); //backtrack
       }
   }
}

/* Driver program to test above functions */
int main()
{
    char str[] = "ABC";
    int n = strlen(str);
    permute(str, 0, n-1);
    return 0;
}

最佳答案

我至少可以想到两种方法。一种是通过置换函数并行化,另一种是通过 rank 并行化。 .

本回答采用第二种方法。对于 n = strlen(str),排列数(又名等级)是 n!。例如。对于 str = "ABCD",等级数是 24。这是一种在排名上执行此操作的方法(基于 this paper ):

#include <string.h>
#include <stdio.h>
#include <stdlib.h>

#define SWAP(a,b) do{t=(a);(a)=(b);(b)=t;}while(0)

void get_permutation(int rank, int n, char *vec) {
    int t, q, r;
    if (n < 1) return;
    q = rank / n;
    r = rank % n;
    SWAP(vec[r], vec[n-1]);
    get_permutation(q, n-1, vec);
}

int main(int argc, char *argv[]) {
  char a[5] = "ABCD", t[5];

  #pragma omp parallel for private(t) schedule(dynamic)
  for (int r = 0; r < 24; ++r) {
    strcpy(t, a);
    get_permutation(r, 4, t);
    #pragma omp critical
    printf("%3d: %s\n", r, t);
  }
}

只要 get_permutation 比输出(在本例中为 printf)慢,此方法就应该在性能上胜出。对于足够大的字符串长度,这将是正确的。

我系统的输出是

  3: BCAD
  6: DABC
  7: CABD
  9: DACB
  8: BDCA
 10: BADC
 11: BACD
 13: CDAB
 14: DBAC
 15: CBAD
 16: DCBA
  1: DCAB
 17: ACDB
 19: ACBD
 20: DBCA
 21: ADCB
 22: ABDC
 23: ABCD
 12: CBDA
  0: BCDA
 18: ADBC
  4: CDBA
  2: BDAC
  5: CADB

关于c - c中的openmp并行递归函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50848981/

相关文章:

c - 在C语言中如何读取这个函数?

json - jQuery:递归删除所有与给定模式匹配的键

c++ - 嵌套循环的 OpenMP 偶数/奇数分解

c++ - OpenMP:同时写入 std::map

c++ - 并行处理碰撞对

c - realloc-call 后没有变化

c++ - 如何在我的程序中检测 GPS 设备连接到的端口(C/C)

c - 在 linux 上,avr 和 linux 之间的串口有问题

c++ - 向后返回的 C++ 递归

recursion - 使用 wget 从网站下载特定类型的所有文件 在起始 url 中停止