蓝桥杯 java算法训练 最小乘积(基本型)

算法训练 最小乘积(基本型)
时间限制:1.0s 内存限制:512.0MB

问题描述
  给两组数,各n个。
  请调整每组数的排列顺序,使得两组数据相同下标元素对应相乘,然后相加的和最小。要求程序输出这个最小值。
  例如两组数分别为:1 3  -5和-2 4 1

那么对应乘积取和的最小值应为:
  (-5) * 4 + 3 * (-2) + 1 * 1 = -25
输入格式
  第一个行一个数T表示数据组数。后面每组数据,先读入一个n,接下来两行每行n个数,每个数的绝对值小于等于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

package 决赛练习题;

import java.util.Arrays;
import java.util.Scanner;

public class 最小乘积基本型 {

public static void main(String[] args) {
	Scanner sc=new Scanner(System.in);
	int T=sc.nextInt();
	int num=0;
	while(T>0) {
		int m=sc.nextInt();
		int A[]=new int[m];
		int B[]=new int[m];
		for(int i=0;i<m;i++) {
			A[i]=sc.nextInt();
		}
		for(int i=0;i<m;i++) {
			B[i]=sc.nextInt();
		}
		Arrays.sort(A);
		Arrays.sort(B);
		for(int i=0;i<m;i++) {
			num+=A[i]*B[m-i-1];
		}
		System.out.println(num);
		num=0;
		T--;
	}
}

}

猜你喜欢

转载自blog.csdn.net/weixin_43557514/article/details/89205878
今日推荐