Code Jam 2008 Round1 A

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
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值