zoukankan      html  css  js  c++  java
  • geeksforgeeks@ Minimum sum partition (Dynamic Programming)

    http://www.practice.geeksforgeeks.org/problem-page.php?pid=166

    Minimum sum partition

    Given an array, the task is to divide it into two sets S1 and S2 such that the absolute difference between their sums is minimum.

    Input:
    The first line contains an integer 'T' denoting the total number of test cases. In each test cases, the first line contains an integer 'N' denoting the size of array. The second line contains N space-separated integers A1, A2, ..., AN denoting the elements of the array.


    Output:
    In each seperate line print minimum absolute difference.


    Constraints:
    1<=T<=30
    1<=N<=50
    1<=A[I]<=50


    Example:
    Input:
    2
    4
    1 6 5 11
    4
    36 7 46 40

    Output : 
    1
    23

    Explaination :
    Subset1 = {1, 5, 6}, sum of Subset1 = 12
    Subset2 = {11},       sum of Subset2 = 11

    import java.util.*;
    import java.lang.*;
    import java.io.*;
    
    class GFG {
        
        public static int func(int[] arr) {
            
            int n = arr.length, tot = 0;
            for(int i=0; i<n; ++i) {
                tot += arr[i];
            }
            int half = tot/2, e = half;
            
            for(; e>=0; --e) {
                boolean[][] dp = new boolean[n + 1][e + 1];
    
                for(int i=0; i<=n; ++i) {
                    dp[i][0] = true;
                }
    
                for(int i=1; i<=n; ++i) {
                    for(int j=1; j<=e; ++j) {
                        if(j >= arr[i - 1]) {
                            dp[i][j] |= dp[i-1][j] | dp[i-1][j - arr[i-1]];
                        }
                        dp[i][j] |= dp[i-1][j];
                    }
                } 
                if(dp[n][e]) break;
            }
            
            //System.out.println(e);
            return Math.abs(e - (tot - e));
        }
        
        public static void main (String[] args) {
            Scanner in = new Scanner(System.in);
            int times = in.nextInt();
            
            while(times > 0) {
                --times;
                
                int n = in.nextInt();
                int[] arr = new int[n];
                for(int i=0; i<n; ++i) {
                    arr[i] = in.nextInt();
                }
                
                System.out.println(func(arr));
            }
        }
    }
    View Code
  • 相关阅读:
    关于git的文件内容冲突解决
    【C++】 四种强制类型转换(static_cast 与 dynamic_cast 的区别!)
    如何判断一个变量是不是指针
    类型识别
    C++中的异常处理(下)
    C++中的异常处理(中)
    C++中的异常处理(上)
    C语言异常处理
    用Zebra打造Linux下小型路由器
    Linux下PortSentry的配置
  • 原文地址:https://www.cnblogs.com/fu11211129/p/5642224.html
Copyright © 2011-2022 走看看