myaw's blog

By myaw, history, 9 years ago, In English

I just solved this dp problem , i compared my code to an accepted code by trying random test cases , and it gives correct results , how ever it gives MLE in the onligne judge ( only 32M of memory )

So my question is how to prevent this ??

My code

Problem statement :

A tug of war is to be arranged at the local office picnic. For the tug of war, the picnickers must be divided into two teams. Each person must be on one team or the other; the number of people on the two teams must not differ by more than 1; the total weight of the people on each team should be as nearly equal as possible.

Input

Input starts with an integer T (≤ 100), denoting the number of test cases.

The first line of each case is a blank line. The next line of input contains an integer n (2 ≤ n ≤ 100), the number of people at the picnic. n lines follow. The first line gives the weight of person 1; the second the weight of person 2; and so on. Each weight is an integer between 1 and 100000. The summation of all the weights of the people in a case will not exceed 100000.

Output

For each case, print the case number and the total number weights of the people in two teams. If the weights differ, print the smaller weight first.

Sample Input

2

3 100 90 200

4 10 15 17 20

Output for Sample Input

Case 1: 190 200 Case 2: 30 32

  • Vote: I like it
  • -3
  • Vote: I do not like it

| Write comment?
»
9 years ago, # |
  Vote: I like it 0 Vote: I do not like it

I've just glanced on your solution. It is really hard to understand for me, and I didn't get the idea. However, it looks like you have dependency like dp(step)=f(dp(step-1)), so you can hold in memory only last layer of memo.

  • »
    »
    9 years ago, # ^ |
      Vote: I like it 0 Vote: I do not like it

    Thanks for the reply , i want to find a solution of MLE in DP rather than finding a solution of this particular problem , the main problem is this memo[100005][101] .

    so is there a way to reduce memory , i heard about using bitmask , or if there is any other way .

    • »
      »
      »
      9 years ago, # ^ |
        Vote: I like it 0 Vote: I do not like it

      Storing only last 2 (or 3,4,...) layers is a common general DP memory optimization which can be applied not only for this particular problem. Speaking of which, you can (from my first look) reduce your array to memo[100005][2], which saves you 37MB and gets to less than 1MB.