c++ - 分区解决太慢

标签 c++ partition-problem

我正在解决一个对我来说看起来像分区问题的问题: 我有一个整数序列,我应该找到一个(如果有多个解决方案,我应该只输出一个)这些整数的子集,使得它们的总和恰好是所有整数总和的一半。

我正在尝试通过动态规划来解决它,但我的解决方案在测试中仍然太慢(我只能通过 2/10 测试,其余的太慢)。感谢您的帮助。

我的代码:

void split(std::vector<int> seq, int sum, FILE * output){
  int n = seq.size() + 1;
  int m = sum + 1;
  bool** matrix = (bool**)malloc(m*sizeof(bool*));
  for(int i = 0;i<m;i++){
    matrix[i] = (bool*)malloc(n*sizeof(bool));
  }


  for(int i=1;i<=m-1;i++){
    matrix[0][i]=false;
  }
  for(int i=0;i<=n-1;i++){
    matrix[i][0]=true;
  }

  for(int i=1;i<=n-1;i++){
    for(int j=1;j<=m-1;j++){
      matrix[i][j] = matrix[i-1][j];
      if(matrix[i][j]==false && j>=seq[i-1])
    matrix[i][j] = matrix[i][j] || matrix[i-1][j-seq[i-1]];
    }
  }

  if(matrix[n-1][m-1]){
    int row = n-1;
    int column = m-1;

    while((row > 1) && (column > 0)){
      while(matrix[row-1][column]){row--;}
      fprintf(output, "%i ", row);
      column = column - seq[row-1];
    }
  }
  else{
    fprintf(output, "no");
  }
}

最佳答案

如果允许另一种方法,您可以尝试使用二叉搜索树。它应该在 O(n log n) 时间内完成,其中 n 是序列的大小。

关于c++ - 分区解决太慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34245505/

相关文章:

algorithm - 将一组值分成两组具有相似值和的相同或相似大小

c++ - 使用IMFSourceReader进行音频流传输(Microsoft Media Foundation)

c++ - 如何测量流水线延迟?

c++ - 在整数数组中连续输入

algorithm - 背包的变体

algorithm - PartitionProblem - 找到最优子集

algorithm - 给定一个整数数组,创建分区,其中每个分区中的元素总和为 0,并且形成最大分区数

c++ - Winsock2 recv() 挂接到远程进程

c++ - malloc 没有按我的预期工作