How can I reduce the time of this program
A very nice question.

Here is the brief idea of a more efficient algorithm. The central idea is how to fill one package and close it with minimal unfilled capacity left. That is a standard knapsack problem that can done efficiently with dynamic programming. 

However, now we have two packages available, each might have different initial capacities available, as you have pointed out. 

What to do? Then do two knapsack problems at the same time!

Right after you have closed one package, you have two packages, one with $a_1$ available capacity and the other with $a_2$ available capacity. We have two knapsack problems here: how to fill the one with $a_1$ capacity as much as possible without bursting the other one and how to fill the one with $a_2$ capacity as much as possible without bursting the other one. Solve them separately. Compare the result to find which one get less free capacity left. Choose that package and its maximal filling found just now and close it. Fill the other one with the items that should have been used before closing the previous one. Repeat the process.

(Further update might come to clarify the above explanation. But this should get you going.)