0

I am solving a problem that looks like partition problem to me: I have a sequence of integers and I should find one (if there are more than one solution I am supposed to output only single one) subset of these integers such that sum of them is exactly half of the sum of all integers.

I am trying to solve it via dynamic programming, but my solution is still too slow in test (I can pass only 2/10 tests and rest is too slow). Thanks for help.

My code:

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");
  }
}
user1505497
  • 321
  • 5
  • 13

1 Answers1

1

If another approach is permitted, you can try by using Binary Search Tree. It should finish in O(n log n) time, where n is size of the sequence.

karastojko
  • 1,156
  • 9
  • 14
  • [Binary Search Tree](https://en.wikipedia.org/wiki/Binary_search_tree) explains the concept. The idea for your case is to make BST, and while making it to store in each node sums of its subtrees. The node with the sum of half of the total sum should contain all the elements. Still, I should calculate if it's faster than the dynamic solution. – karastojko Dec 12 '15 at 22:23
  • 1
    The idea is for such created BST to go in parallel from the leftmost and rightmost nodes and check the sums of the subtrees. Still, it's not good approach, an example can be created which cannot be calculated this way. – karastojko Dec 12 '15 at 23:00