Google Code Jam Notes - Minimum Scalar Product - Java

来源:互联网 发布:ppt数据展示模板 编辑:程序博客网 时间:2024/04/30 13:45
Problem:
Retrieved from: http://code.google.com/codejam/contest/32016/dashboard#s=p0

You are given two vectors v1=(x1,x2,...,xn) and v2=(y1,y2,...,yn). The scalar product of these vectors is a single number, calculated as x1y1+x2y2+...+xnyn.

Suppose you are allowed to permute the coordinates of each vector as you wish. Choose two permutations such that the scalar product of your two new vectors is the smallest possible, and output that minimum scalar product.

Input

The first line of the input file contains integer number T - the number of test cases. For each test case, the first line contains integer number n. The next two lines contain nintegers each, giving the coordinates of v1 and v2 respectively.

Output

For each test case, output a line

Case #X: Y
where X is the test case number, starting from 1, and Y is the minimum scalar product of all permutations of the two given vectors.

Limits

Small dataset

T = 1000
1 ≤ n ≤ 8
-1000 ≤ xiyi ≤ 1000

Large dataset

T = 10
100 ≤ n ≤ 800
-100000 ≤ xiyi ≤ 100000

Sample


Input 
 
Output 
 2
3
1 3 -5
-2 4 1
5
1 2 3 4 5
1 0 1 0 1

Case #1: -25
Case #2: 6


Analysis:
This is actually a mathematical problem, the fact is if we have two arrays in natural order:
(x1, x2, x3, x4) and (y1, y2, y3, y4)
The minimum scalar product is: x1* y4 + x2*y3 + x3*y2 + x4*y1
The maximum scalar product is: x1*y1 + x2*y2 + x3* y3 + x4*y4   

My solution: (Your opinion is highly appreciated)

package codeJam.google.com;import java.io.BufferedReader;import java.io.FileReader;import java.io.FileWriter;import java.io.IOException;import java.util.Arrays;/** * @author Zhenyi 2013 Dec 21, 2013 14:45:21 PM */public class MinimumScalarProduct {public static void main(String[] args) throws IOException {BufferedReader in = new BufferedReader(new FileReader("C:/Users/Zhenyi/Downloads/A-small-practice.in"));FileWriter out = new FileWriter("C:/Users/Zhenyi/Downloads/A-small-practice.out");// BufferedReader in = new BufferedReader(new// FileReader("C:/Users/Zhenyi/Downloads/A-large-practice.in"));// FileWriter out = new// FileWriter("C:/Users/Zhenyi/Downloads/A-large-practice.out");int N = new Integer(in.readLine());for (int cases = 1; cases <= N; cases++) {int num = new Integer(in.readLine());String[] sta = new String(in.readLine()).split("\\s");String[] stb = new String(in.readLine()).split("\\s");long a[] = new long[num];for (int i = 0; i < num; i++) {a[i] = new Long(sta[i]);}long b[] = new long[num];for (int i = 0; i < num; i++) {b[i] = new Long(stb[i]);}long result = 0;Arrays.sort(a);Arrays.sort(b);for (int i = 0; i < a.length; i++) {result = result + a[i] * b[b.length - i - 1];}out.write("Case #" + cases + ": " + result + "\n");}in.close();out.flush();out.close();}}


0 0