Prerequisite :- Dynamic Programming,Recursion.
Problem :- Given N pairs of books, The problem is about dividing pairs of books between Lavanya and Nikhil so that the difference in the total value of books assigned to them is minimized. Each pair of books has a cost, and Lavanya’s father needs to distribute them in a way that the total value of books for Lavanya is as close as possible to that of Nikhil. The task is to find the smallest possible difference between the total values assigned to Lavanya and Nikhil.
Explanation : -
Recursive approach to all possible combinations of assigning books to Lavanya and Nikhil.
At each step of the recursion, consider two choices: assigning the current book pair to Lavanya or to Nikhil.
By recursively exploring these choices for each book pair, the solution aims to find the combination that minimizes the difference in total book values assigned to Lavanya and Nikhil.
Memoization (Dynamic Programming):
To optimize the recursive approach, the solution uses memoization.
Memoization helps avoid redundant calculations by storing the results of already computed subproblems.
By storing these results in a table, the solution can quickly retrieve them when needed during the recursion, reducing the overall time complexity.
Base Case:
The recursion terminates when all book pairs have been considered.
At this point, the solution calculates the difference in total book values assigned to Lavanya and Nikhil and returns it as the result.
Choosing the Minimum:
- During the recursion, consider two options for each book pair: assigning it to Lavanya or to Nikhil.
- Choose the option that results in the minimum difference in total book values between Lavanya and Nikhil.
- This ensures that the final result represents the smallest possible difference in total book values assigned to Lavanya and Nikhil.
C++ Solution :-
#include <bits/stdc++.h>
using namespace std;
int solve(int pos, int sum, vector < vector < int >> & dp, vector < pair < int, int >> & v) {
if (pos == v.size()) return sum;
if (dp[pos][sum] != -1) return dp[pos][sum];
int dif = v[pos].first - v[pos].second;
dif = abs(dif);
int fans = INT_MAX;
fans = solve(pos + 1, dif + sum, dp, v);
fans = min(solve(pos + 1, abs(dif - sum), dp, v), fans);
return dp[pos][sum] = fans;
}
int main() {
// your code goes here
vector < pair < int, int >> v;
int n;
cin >> n;
for (int i = 0; i < n; i++) {
int n1, n2;
cin >> n1 >> n2;
v.push_back({
n1,
n2
});
}
vector < vector < int >> dp(n, vector < int > (n * 300 + 1, -1));
cout << solve(0, 0, dp, v);
}