单点时限: 2.0 sec
内存限制: 256 MB
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.
输入格式
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 n integers each, giving the coordinates of v1 and v2 respectively.
T = 10
100 ≤ n ≤ 800
-100000 ≤ xi, yi ≤ 100000
输出格式
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.
样例
input
2 3 1 3 -5 -2 4 1 5 1 2 3 4 5 1 0 1 0 1
output
Case #1: -25 Case #2: 6
#include <iostream>
#include <bits/stdc++.h>
#include <math.h>
using namespace std;
class SingleJob{
public:
int dim;
vector<long long> vecA;
vector<long long> 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);
}
}
// 输出。注意结果dotpdt是两个int型相乘,需要用longlong定义
long long 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());
for(int j=0;j<J[i].dim;j++){
dotpdt += J[i].vecA[j] * J[i].vecB[j];
}
cout << "Case #" << i+1 << ": " << dotpdt << endl;
dotpdt = 0;
}
return 0;
}
ps:假设维度是n,让A、B生成全排列然后暴力解的时间复杂度是O()。注意到最小点积可以是 “让每个vecA最大的数 × vecB最小的数” 从而简化运算。
因此本例将vecA递增排序、vecB递减排序,最后求出每个job对应的点积 dotpdt 并输出。
另外,本题与 EOJ3003. 最小向量点积 的不同之处在于vectorA和vectorB 的范围扩大了,导致的点积结果可能超过int所表示的范畴