标签:algo-53 最小乘积基本型 算法 蓝桥杯 java
说明:蓝桥杯官网上的“样例输入”和“样例输出”格式不对,我在这里改成了对的格式
分析:
1、两组数,一组数从小到大排序,另一组数从大到小排序,然后按相同下标对应相乘再求和,即为最小值
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int t = scanner.nextInt(); while (t-- != 0) { int n = scanner.nextInt(); int[] nums1 = new int[n]; int[] nums2 = new int[n]; for (int i = 0; i < n; i++) { nums1[i] = scanner.nextInt(); } for (int i = 0; i < n; i++) { nums2[i] = scanner.nextInt(); } sortSmallToLarge(nums1, 0, n - 1); sortLargeToSmall(nums2, 0, n - 1); int result = 0; for (int i = 0; i < n; i++) { result += nums1[i] * nums2[i]; } System.out.println(result); } } private static void sortLargeToSmall(int[] nums2, int start, int end) { if (start >= end) { return; } int key = nums2[start]; int i = start + 1, j = end; while (true) { while (i <= end && nums2[i] >= key) { i++; } while (j > start && nums2[j] <= key) { j--; } if (i < j) { swap(nums2, i, j); } else { break; } } swap(nums2, start, j); sortLargeToSmall(nums2, start, j - 1); sortLargeToSmall(nums2, j + 1, end); } private static void sortSmallToLarge(int[] nums1, int start, int end) { if (start >= end) { return; } int key = nums1[start]; int i = start + 1, j = end; while (true) { while (i < end && nums1[i] <= key) { i++; } while (j > start && nums1[j] >= key) { j--; } if (i < j) { swap(nums1, i, j); } else { break; } } swap(nums1, start, j); sortSmallToLarge(nums1, start, j - 1); sortSmallToLarge(nums1, j + 1, end); } private static void swap(int[] nums2, int i, int j) { if (i == j) { return; } int temp = nums2[i]; nums2[i] = nums2[j]; nums2[j] = temp; } }
[ALGO-53] 最小乘积(基本型),布布扣,bubuko.com
标签:algo-53 最小乘积基本型 算法 蓝桥杯 java
原文地址:http://blog.csdn.net/u011506951/article/details/27182867