You are given an array of elements . If you are considering index , then you contain a set of all elements whose index is not equal to . Your task is to find out if you can express as the sum of subsets of .
For example, you have elements such as and you consider index . Therefore, set is because you have to exclude the element at index . The answer is Yes because you select subset and its sum is . Suppose, if you consider index , then set is . The answer is Yes because you can select , , , or .
Similarly, the answer for is No because set is and there is no possible way such that you can select a subset and have sum .
Note that you can select no more times than it occurs in set .
You are given array . For every index, your task is to determine if it is possible for index from to .
Example:
Input: n=8, arr[]= { 1, 2, 3, 4, 5, 6, 7, 8 }
Output: 0 0 1 1 1 1 1 1
Approach
Java
import java.util.Arrays;public class ArraysSums {public static void main(String[] args) {int n = 8;int arr_org[] = { 1, 2, 3, 4, 5, 6, 7, 8 };int arr[] = arr_org;Arrays.sort(arr);isSubsetSum(arr, n, 1000);for (int i = 0; i < n; i++) {if (subset[arr_org[i]][binarySearch(arr_org[i], n, arr)])System.out.print("1 ");elseSystem.out.print("0 ");}}static boolean[][] subset;// binary searchstatic int binarySearch(int i, int n, int[] arr) {int l = 0;int r = n;int mid = l + r / 2;while (l < r) {mid = (l + r) / 2;if (arr[mid] > i) {r = mid;} else {l = mid + 1;}}return l - 1;}// calculate the sub setstatic boolean isSubsetSum(int set[], int n, int sum) {subset = new boolean[sum + 1][n + 1];for (int i = 0; i <= n; i++)subset[0][i] = true;for (int i = 1; i <= sum; i++)subset[i][0] = false;for (int i = 1; i <= sum; i++) {for (int j = 1; j <= n; j++) {subset[i][j] = subset[i][j - 1];if (i >= set[j - 1])subset[i][j] = subset[i][j] || subset[i - set[j - 1]][j - 1];}}return subset[sum][n];}}
No comments:
Post a Comment