如何使用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