Hey there, since things are getting a little more calm, I can focus once more to solve some nice Code Jam problems. And here we go, from the first official tournament round: Problem A: Minimum Scalar Product. It says:
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.
There’s a catch on the text, that made me quite confused. In case you didn’t notice, it’s that damn TWO PERMUTATIONS part. Despite getting the sample results right, when the bigger test cases came, I wasn’t able to get the smallest results right! Because, guess why, I was only doing two value permutations, because to me, the text says so!
Anyway, took a look into the results and saw that participants were simply not considering this limitation and outputting the minimum possible value anyway and to hell with it. If Google thinks this would be the correct approach, who am I to judge! 😀 Just sort both arrays, invert one of them, iterate calculating the MSP and you’re done! Python code, as usual:
for case in range(1,int(raw_input())+1): # For all test cases size = int(raw_input()) # Since we're informed, save array size x = map(int, raw_input().split(" ")) # Get all X parameters y = map(int, raw_input().split(" ")) # Get all Y parameters x.sort() # Sort both vectors y.sort() # And sort-reverse Y y.reverse() # So we can match the bigger/smaller values msp = 0 for i in range(size): # For all the array's len msp += x[i]*y[i] # Sum "forward" on X and "backwards" on Y print "Case #%d: %d" % (case, msp) # Print the sum
And that’s it! Quick and easy, despite the text hiccup. Githubbin’ it. See you!
ya.,,. thank you.,,.
this is ridiculous ..,.