EOJ3003. Minimum vector dot product

Single point time limit:  2.0 sec

Memory limit:  256 MB

The dot product of two vectors a=[a1,a2,⋯,an] and b=[b1,b2,⋯,bn] is defined as:

For example, the dot product of two three-dimensional vectors [1,3,−5] and [4,−2,−1] is

Assume that the coordinate values ​​in each vector are allowed to be rearranged. Find the permutation with the smallest dot product among all permutations, and output the smallest dot product value.

One permutation in the example above, [3,1,−5] and [−2,−1,4], has a dot product of −27, which is the smallest dot product.

Input format

Line 1: An integer T (1⩽T⩽10) is the number of questions.

Each question next has 3 lines. Line 1 is an integer n (1⩽n⩽1000), representing the dimensions of the two vectors. Lines 2 and 3 represent vector a and vector b respectively. Each vector consists of n coordinate values ​​coordinate values ​​(−1000 ⩽ coordinate value ⩽ 1000) separated by a space.

Output format

For each question, output a line of question numbers (0-based numbering, format: case #0: etc.).

Then output the minimum dot product value in one row for each problem.

Sample

input

3
3
3 1 -5
-2 -1 4
1
2
-298
5
1 2 3 4 5
1 0 1 0 1

output

case #0:
-27
case #1:
-596
case #2:
6

Problem-solving ideas

        Assuming that the dimension is n, the time complexity of letting A and B generate the full arrangement and then solve it violently is O( n^2). Note that the minimum dot product can be "let the largest number in vecA × the smallest number in vecB" to simplify the operation.

        Therefore, in this example, vecA is sorted in ascending order, vecB is sorted in descending order, and finally the dot product dotpdt corresponding to each job is found and output.

Sample code

#include <iostream>
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
class SingleJob{
public:
	int dim;
	vector<int> vecA; 
	vector<int> vecB;
};

int main() {
    int jobs, temp;
    SingleJob J[10];
    // 输入
    cin >> jobs;
	for(int i=0;i<jobs;i++){
		cin >> J[i].dim;
		for(int j=0;j<J[i].dim;j++){
			cin >> temp;
			J[i].vecA.insert(J[i].vecA.end(), temp);
		}
		for(int j=0;j<J[i].dim;j++){
			cin >> temp;
			J[i].vecB.insert(J[i].vecB.end(), temp);
		}
	}	
	// 输出
	int dotpdt=0;
	for(int i=0;i<jobs;i++){
		sort(J[i].vecA.begin() , J[i].vecA.end());
		sort(J[i].vecB.rbegin(), J[i].vecB.rend());
		cout << "case #" << i << ":" << endl;
		for(int j=0;j<J[i].dim;j++){
			dotpdt += J[i].vecA[j] * J[i].vecB[j];
		}	
		cout << sql << endl;
		dotpdt = 0;
	}
	return 0;
}   

 

Guess you like

Origin blog.csdn.net/qingxiu3733/article/details/131754807