题目描述:
Problem
You are given two vectors v 1 v1 v1 = (x1, x2, …, xn) and v 2 v2 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 n integers 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
Time limit: 30 1 second(s) per test set.
Memory limit: 1GB.
Small dataset (Test set 1 - Visible; 5 Points)
T = 1000
1 < n < 8
-1000 < xi, yi < 1000
Large dataset (Test set 2 - Hidden; 10 Points)
T = 10
100 < n < 800
-100000 < xi, yi < 100000
Sample
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
题目大意:
有两个向量 v 1 v1 v1 = = = ( ( ( x 1 x_1 x1, x 2 x_2 x2,…, x n x_n xn ) ) )和 v 2 v2 v2 = = = ( ( ( y 1 y_1 y1, y 2 y_2 y2,…, y n y_n yn ) ) ),允许任意交换 v 1 v1 v1 和 v 2 v2 v2各自的分量顺序。请计算 v 1 v1 v1和 v 2 v2 v2的内积 ∑ i = 1 n x i y i \displaystyle\sum_{i = 1}^{n}x_{i}y_{i} i=1∑nxiyi
题解:
由于
v
1
v1
v1和
v
2
v2
v2的顺序均不固定,我们可以先将v1的顺序固定下来(为了方便,将v1升序排列)。一种朴素的想法是对
v
2
v2
v2中的数进行全排列,一共有
n
!
n!
n!种排列,总的时间复杂度为
O
(
n
!
∗
n
)
O(n! * n)
O(n!∗n),在Large的情况下会超时,需要我们换思路。
我们先在
v
1
v1
v1,
v
2
v2
v2中找两组数
(
x
i
,
x
j
)
(x_i, x_j)
(xi,xj)
(
y
i
,
y
j
)
(y_i, y_j)
(yi,yj)保证
i
<
j
i<j
i<j则有两种匹配方式
(
(
(
x
i
x_i
xi
y
i
+
x
j
y
j
y_i + x_jy_j
yi+xjyj和
x
i
y
j
+
x
j
y
i
x_iy_j + x_jy_i
xiyj+xjyi
)
)
)
x
i
y
i
+
x
j
y
j
−
x
j
y
i
−
x
i
y
j
=
(
x
i
−
x
j
)
(
y
i
−
y
j
)
x_iy_i + x_jy_j - x_jy_i - x_iy_j = (x_i - x_j)(y_i - y_j)
xiyi+xjyj−xjyi−xiyj=(xi−xj)(yi−yj)
要保证内积最小则
y
i
y_i
yi应该大于等于
y
j
y_j
yj
因此我们只需要将
v
2
v2
v2降序排列计算即可
代码如下:
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const int N = 805;
int v1[N];
int v2[N];
int main(){
int T, t, n;
long long ans = 0;
scanf("%d", &T);
for(t = 1; t <= T; t++){
scanf("%d", &n);
for(int i = 1; i <= n; i++)
scanf("%d", &v1[i]);
for(int i = 1; i <= n; i++)
scanf("%d", &v2[i]);
sort(v1 + 1, v1 + n + 1);
sort(v2 + 1, v2 + n + 1);
ans = 0;
for(int i = 1; i <= n;i++)
ans += ((long long)v1[i]) * v2[n - i + 1];
printf("Case #%d: %ld\n",t, ans);
}
}
注:代码中将 v 1 v1 v1和 v 2 v2 v2均升序排, v 2 v2 v2倒过来取值