[ALGO-53] 最小乘积(基本型)

时间:2014-06-05 04:39:00   收藏:0   阅读:264

算法训练 最小乘积(基本型)  
时间限制: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

说明:蓝桥杯官网上的“样例输入”和“样例输出”格式不对,我在这里改成了对的格式


分析:

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

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!