Meet in the Middle | CSES - Algoritmit ongelmanratkaisussa
https://cses.fi/alon/task/1628 #include #include #include #include using namespace std ; int dp [ 41 ] [ 41 ] ; int n ; long long x ; long long arr [ 41 ] ; vector getSubsetSum ( int l , int r ) { int len = r - l + 1 ; vector res ; for ( int i = 0 ; i
In the coding challenge CSES - Algorithm Problem Solving, a solution is presented in C++ that calculates the number of ways to partition an array into two subsets with a specific sum. The algorithm utilizes dynamic programming and binary search techniques.
First, the necessary header files are included, and the required data structures, such as vectors and arrays, are declared. The `dp` array is initialized to store intermediate results, while `n` represents the size of the input array `arr`. The variable `x` denotes the target sum for the partition.
A helper function `getSubsetSum` is defined, which takes the left and right indices of the array and returns a vector containing all possible subset sums within that range. This function uses bit manipulation to generate all possible combinations of elements and calculates their sums.
In the `main` function, the input size `n` and the target sum `x` are read from standard input. The array elements are then inputted, and two vectors, `left` and `right`, are created to store the subset sums of the first half and the second half of the array, respectively.
Both `left` and `right` vectors are sorted in ascending order. The algorithm then iterates through each element `i` in the `left` vector. For each element, binary search is performed on the `right` vector to find the lower and upper bounds of the values that, when subtracted from `i`, equal the target sum `x`. The difference between the upper and lower bounds represents the number of valid ways to partition the array.
Finally, the total count of ways is stored in the `ways` variable and printed to standard output. The program terminates with a return value of 0.
Rewritten by urgent.news; may contain errors — check the original.
Source: dev.to