Google code jam exercise -- Minimum Scalar Product

Source: Internet
Author: User

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()

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.