google code jam exercise——Minimum Scalar Product

來源:互聯網
上載者:User

繼續Python練習。這次的題很簡單的。

這次的題是Minimum Scalar Product,大概意思是給你兩個數組va和vb,兩個數組的元素對應相乘,然後求和,要求和最小,在數組元素順序可以調整的時候。

這裡主要用到一個不等式,x和y兩個升序的數組,那麼sum(x[i]*y[i])>=sum(x[i]*y[n-i]),這個不等式在元素中有負數時也是成立的,所以問題的解法就很直接了。

Python裡面可以直接調用sort和reverse函數,先將兩個數組va和vb排序,然後將其中一個reverse一下,在把元素對應相乘,就得到最小值了。

代碼如下:

#!/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()

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.