Continue with the Python exercise. This question is very simple.
This question is Minimum Scalar Product. It probably means to multiply the elements of two arrays, va and vb, and then sum the values, and the Minimum value, when the order of array elements can be adjusted.
Here we mainly use an inequality, which is an array in ascending order of x and y. Then sum (x [I] * y [I])> = sum (x [I] * y [n-I]), this inequality is also true when there is a negative number in the element, so the solution to the problem is very direct.
In Python, you can directly call the sort and reverse functions. First, sort the two arrays va and vb, and then reverse one of them. After the elements are multiplied, the minimum value is obtained.
The Code is as follows:
#!/usr/bin/python
#encoding:UTF-8
#Filename:MinimumScalarProduct.py
import sys
inname = "input.txt"
outname = "output.txt"
if len(sys.argv)>1:
inname = sys.argv[1]
outname = inname.rstrip(".in")
outname = outname + ".out"
testCaseNum = 0
fin = open(inname,"r")
line = fin.readline()
testCaseNum = int(line)
fout = open(outname,"w")
caseNum = 0
for caseNum in range(testCaseNum):
line = fin.readline()
vectorLen = int(line)
line = fin.readline()
va = [int(val) for val in line.split()]
line = fin.readline()
vb = [int(val) for val in line.split()]
va.sort()
vb.sort()
vb.reverse()
sp = 0
for j in range(vectorLen):
sp = sp + va[j] * vb[j]
answer = "Case #%d: %d\n" %(caseNum+1,sp)
fout.write(answer)
fin.close()
fout.close()