分区解决方案太慢

Partition solution too slow

本文关键字:解决方案 分区      更新时间:2023-10-16

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

我试图通过动态编程来解决它,但我的解决方案在测试中仍然太慢(我只能通过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是序列的大小。

相关文章: