• Source
    1. #include<stdio.h>
    2. #include<cstring>
    3. #include<iostream>
    4. using namespace std;
    5. // assuming maximum subscribers and books is 1000
    6. int dp[1001][1001],pages[1001],n,m;
    7. //dp[][] is memset to -1 from main
    8. // Assuming books are numbered 1 to n
    9. // change value of MAX based on your constraints
    10. int MAX = 1000000000;
    11. int rec(int position , int sub )
    12. {
    13. // These two are the base cases
    14. if(position > n)
    15. {
    16. if(sub == 0)return 0;
    17. return MAX;
    18. }
    19. if(sub == 0)
    20. {
    21. if(position > n)return 0;
    22. return MAX;
    23. }
    24.  
    25. // If answer is already computed for this state return it
    26. if(dp[position][sub] != -1)return dp[position][sub];
    27.  
    28. int ans = MAX,i,sum = 0;
    29. for(i = position; i <= n;i++)
    30. {
    31. sum += pages[i];
    32. // taking the best of all possible solutions
    33. ans = min(ans,max(sum,rec(i+1,sub-1)));
    34. }
    35. dp[position][sub]=ans;
    36. return ans;
    37. }
    38.  
    39. int main()
    40. {
    41. int test,i,start,ans,pos,sum;
    42. cin >> test;
    43. while(test -- )
    44. {
    45. cin >> n >> m;
    46. memset(dp,-1,sizeof(dp));
    47. for(i = 1;i <=n ;i++) cin >> pages[i];
    48.  
    49. // This is the minimized maximum number of
    50. // pages any subscriber gets
    51. cout << rec(1,m) <<endl;
    52.  
    53.  
    54. // Now printing the assignment,
    55. // basically the part you were looking for
    56. // Once dp array is filled its easy to find an optimal assignment
    57. start = 1;
    58. while( start <= n )
    59. {
    60. ans = MAX,pos=-1,sum=0;
    61. for(i = start; i <= n; i++)
    62. {
    63. sum += pages[i];
    64. if(ans > max(sum ,rec(i+1,m-1)))
    65. {
    66. ans = max(sum,rec(i+1,m-1));
    67. pos = i;
    68. }
    69. }
    70. m--;
    71. for(i = start;i <= pos;i++)cout << pages[i] << " ";
    72. cout << " / ";
    73. start = pos+1;
    74. }
    75. cout << endl;
    76. }
    77. return 0;
    78. }