Code Jam 2008 Round1 A
Minimum Scalar Product
1.原题
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.
有两个向量,需要计算其向量内积。在可以任意改变向量中元素的位置的情况下,问内积最小是多少?
2.分析
取第一个向量中,最小的元素,乘上第二个向量中最大的元素,直到遍历完整个向量,求积累加就好
3.代码
import os
os.system('cls')
def single_solution(a):
v_len = int(a.readline().strip())
v1 = list(map(int, a.readline().strip().split()))
v2 = list(map(int, a.readline().strip().split()))
flag = 0
product = 0
while flag < v_len:
v1_min = min(v1)
v2_max = max(v2)
product += v1_min * v2_max
v1.remove(v1_min)
v2.remove(v2_max)
flag += 1
return product
def multi_solution(file_input):
infile = open(file_input, "r")
case_num = int(infile.readline())
flag = 1
if os.path.exists("result.out"):
os.remove("result.out")
while flag <= case_num:
result = single_solution(infile)
# print("Case #", flag, ":", result)
with open("result.out", 'a') as f:
f.writelines(["Case #", str(flag), ": ", str(result), "\n"])
f.close
flag += 1
fi = "A-large-practice.in"
multi_solution(fi)
4.结果
这里用的是大数据集,测试正确
Case #1: -7839202227936
Case #2: 7999201712083
Case #3: -1313429236847
Case #4: -3710387739618
Case #5: -3414920765916
Case #6: -1271937742993
Case #7: -1964394407029
Case #8: -1884282427866
Case #9: -4044533757860
Case #10: -838783451371