美文网首页
调整数组使差最小

调整数组使差最小

作者: asdfgjsrgdf | 来源:发表于2019-10-17 11:43 被阅读0次
描述
动态规划----限制商品个数的背包问题,参考:https://blog.csdn.net/L__ear/article/details/86757928
import java.util.Scanner;

public class Main {
    public static void main(String args[]){
        int[] array;
        Scanner sc = new Scanner(System.in);
        int case_num = sc.nextInt();
        sc.nextLine();
        while(case_num>0) {
            String[] tempA = sc.nextLine().split(" ");
            String[] tempB = sc.nextLine().split(" ");
            array = new int[tempA.length+tempB.length];
            for(int i=0;i<tempA.length;i++) {
                array[i] = Integer.parseInt(tempA[i]);
            }
            for(int j=tempA.length;j<tempA.length+tempB.length;j++) {
                array[j] = Integer.parseInt(tempB[j-tempA.length]);
            }
            
        
        
        int[] a = new int[array.length];
        for(int i=0;i<array.length;i++)
            a[i] = array[i];
        int min = a[0];
        for(int i=1;i<a.length;i++) {
            if(a[i]<min) {
                min = a[i];
            }
        }
        for(int i=0;i<a.length;i++)
            a[i] -= min;
        select(a);
        case_num --;
        
        }
        sc.close();
    }

    public static void select(int[] a) {
        int i,j,v;
        int imax = a.length;
        int jmax = imax/2;
        int suma = 0;
        
        for(i=0;i<a.length;i++) {
            suma += a[i];
        }
        int vmax = suma / 2;
        int[][] dp = new int[jmax+1][vmax+1];
        int[][] sel = new int[jmax+1][vmax+1];
        for(j=0;j<=jmax;j++) {
            for(v=0;v<=vmax;v++) {
                if(j==0) {
                    dp[j][v] = 0;
                }
                else {
                    dp[j][v] = -1;
                }
                sel[j][v] = 0;
            }
        }
        for(i=1;i<=imax;i++) {
            for(j=i>jmax?jmax:i;j>=1;j--) {
                for(v = a[i-1];v<=vmax;v++) {
                    if(dp[j-1][v-a[i-1]]<0)
                        continue;
                    else if(dp[j-1][v-a[i-1]]+a[i-1]>dp[j][v]) {
                        dp[j][v] = dp[j-1][v-a[i-1]] + a[i-1];
                        sel[j][v] = sel[j-1][v-a[i-1]] | (1<<(i-1));
                    }
                }
            }
        }
        System.out.println(suma-2*dp[jmax][vmax]);
    }
    
}

相关文章

网友评论

      本文标题:调整数组使差最小

      本文链接:https://www.haomeiwen.com/subject/ynymmctx.html