
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sum Over Subsets using Dynamic Programming in C++
In this problem, we are given an array arr[] of size 2n. Our task is to create a program to find the sum over subset using dynamic programming to solve it.
We need to calculate function, F(x) = Σ Ai such that x&i == i for all x. i.e. i is a bitwise subset of x.
Let’s take an example to understand the problem,
Input: A[] = {5, 7, 1, 9} , n = 2
Output: 5 12 6 22
Explanation: For n = 2 , there are 4 values of x. They are 0, 1, 2, 3.
Now, calculating values of the function:
F(0) = A0 = 5
F(1) = A0 + A1 = 5 + 7 = 12
F(2) = A0 + A2 = 5 + 1 = 6
F(3) = A0 + A1 + A2 + A3 = 5 + 7 + 1 + 9 = 22
The solution to this problem using dynamic programming, we will look at the mask and find a bitwise subset of every mask. We will store the bitwise subset using dynamic programming, which will reduce the number of repetitions. An index that has a set bit or an unset bit will be visited by 2n masks more than once.
We will recur based on the bit at i index:
When i-th bit is set :
DP(mask, i) = DP(mask, i-1) U DP(mask 2i, i-1)
When i-th bit is unset :
DP(mask, i) = DP(mask, i-1)
Program to illustrate the working of our solution,
Example
#include <iostream> using namespace std; const int N = 1000; void SumOverSubsets(int a[], int n) { int sum[1 << n] = {0}; int DP[N][N]; for (int i = 0; i < (1 << n); i++) { for (int j = 0; j < n; j++) { if (i & (1 << j)) { if (j == 0) DP[i][j] = a[i] + a[i ^ (1 << j)]; else DP[i][j] = DP[i][j - 1] + DP[i ^ (1 << j)][j - 1]; } else { if (j == 0) DP[i][j] = a[i]; else DP[i][j] = DP[i][j - 1]; } } sum[i] = DP[i][n - 1]; } for (int i = 0; i < (1 << n); i++) cout<<sum[i]<<"\t"; } int main() { int A[] = {5, 7, 1, 9}; int n = 2; cout<<"The sum over subsets is \t"; SumOverSubsets(A, n); return 0; }
Output
The sum over subsets is 5 12 6 22