c - 组合并行化

标签 c algorithm mpi openmp

我有一段代码可以打印来自 N (nCm) 的 M 数的组合;

由于是递归,所以当N很大时,速度会很慢。

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

#define N  80
#define M  4

int result[M]= {0}; // THE ARRAY THAT SAVE THE RESULT OF ONE COMBINATION
int queue[N] = {0};
int top = 0;

void comb(int* input,int s, int n, int m)
{
    if (s > n)
        return ; 

    if (top == m)
    {
        for (int i = 0; i < m; i++)
        {
            result[i] = queue[i];
            printf("%d\n", queue[i]);
        }
     }

     queue[top++] = input[s];
     comb(input,s+1, n, M);
     top--;
     comb(input,s+1, n, M);
}

int main()
{  
   int array[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,
                  27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,
                  50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,
                  73,74,75,76,77,78,79,80};

    printf("\ncombination():\n");
    comb(array,0, N, M);
    printf("\n");
}

我想知道上面的算法还有没有改进的空间? 如果可能的话,我可以使用 openMP 吗?

谢谢

最佳答案

对我来说,你的代码甚至给出了所需的输出。 see

我变了

  1. 每种组合的打印格式都不够好。
  2. 重复组合。 (注:添加了 if 语句的 else 部分)。
  3. 通过循环和递归调用减少了 2 次递归调用。 (空间较小。)

所需的代码是:

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

#define N  20
#define M  6

int result[M]= {0}; // THE ARRAY THAT SAVE THE RESULT OF ONE COMBINATION
int queue[N] = {0};
int top = 0;

void comb(int* input,int s, int n, int m)
{
    if (s > n)
        return ; 

    if (top == m)
    {
        printf("\n");
        for (int i = 0; i < m; i++)
        {
            result[i] = queue[i];
            printf("%d ", queue[i]);
        }
     }else{
         for(int ss=s;ss<n;ss++){
            queue[top++] = input[ss];
            comb(input,ss+1, n, m);
            top--;
         }
         //comb(input,s+1, n, m);   
     }
}

int main()
{  
   int array[] = {1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,
                  27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,
                  50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,
                  73,74,75,76,77,78,79,80};

    printf("\ncombinations():\n");
    comb(array,0, N, M);
    printf("\n");
}

关于c - 组合并行化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39868415/

相关文章:

c - 在 double 组上使用 memset(…, 0, …) 是否合法?

c++ - Rust 中从 extern "C"方法返回动态字符串以供 C 或 C++ 使用的最佳方法

c++ - 什么数据结构通常用于hold to hash table for a hashmap

gcc - 我们可以使用 gcc 优化标志而不是 mpicc 吗?

c - 诸如 "sequence-point"或 "int a=4,*ptr=&a;"之类的语句是否存在 "x+=4,y=x*2;"问题?

c - 为什么 8 位字段具有字节顺序?

javascript - 优化的合并排序比快速排序更快

java - while循环内排序的时间复杂度

c - MPI C 中每个进程生成的随机数

database - MPI如何发送和接收SQLite数据库