问题描述
给两组数,各n个。
请调整每组数的排列顺序,使得两组数据相同下标元素对应相乘,然后相加的和最小。要求程序输出这个最小值。
例如两组数分别为:1 3 -5和-2 4 1
那么对应乘积取和的最小值应为:
(-5) * 4 + 3 * (-2) + 1 * 1 = -25
请调整每组数的排列顺序,使得两组数据相同下标元素对应相乘,然后相加的和最小。要求程序输出这个最小值。
例如两组数分别为:1 3 -5和-2 4 1
那么对应乘积取和的最小值应为:
(-5) * 4 + 3 * (-2) + 1 * 1 = -25
输入格式
第一个行一个数T表示数据组数。后面每组数据,先读入一个n,接下来两行每行n个数,每个数的绝对值小于等于1000。
n<=8,T<=1000
n<=8,T<=1000
输出格式
一个数表示答案。
样例输入
2 3 1 3 -5 -2 4 1 5 1 2 3 4 5 1 0 1 0 1
样例输出
-25
6
1 import java.text.DecimalFormat; 2 import java.text.NumberFormat; 3 import java.util.ArrayList; 4 import java.util.Arrays; 5 import java.util.Collection; 6 import java.util.Collections; 7 import java.util.List; 8 import java.util.Scanner; 9 import java.util.Stack; 10 public class Main{ 11 public static void main(String[] args){ 12 Scanner input = new Scanner(System.in); 13 int n = input.nextInt(); 14 for(int i=0;i<n;i++){ 15 int m = input.nextInt(); 16 int[] a = new int[m]; 17 int[] temp = new int[m]; 18 int[] b = new int[m]; 19 for(int j=0;j<m;j++){ 20 a[j] = input.nextInt(); 21 } 22 for(int j=0;j<m;j++){ 23 temp[j] = input.nextInt(); 24 } 25 Arrays.sort(a); 26 Arrays.sort(temp); 27 for(int j=m-1;j>=0;j--){ 28 b[m-j-1] = temp[j]; 29 } 30 int sum = 0; 31 for(int j=0;j<m;j++){ 32 sum = sum+a[j]*b[j]; 33 } 34 System.out.println(sum); 35 } 36 37 } 38 }