Code Jam - Store Credit for Python

来源:互联网 发布:知乎的缺点 编辑:程序博客网 时间:2024/05/21 06:20

这道题是Code Jam Africa 2010, Qualification Round的原题,现被用于练习

(https://code.google.com/codejam/contest/351101/dashboard#s=p0)

1.题目

Problem:

你在商店中有C元的消费额度,并且需要买两件商品。首先,你逛了一下商店后列出了L个商品在你的意向中。你需要在这个列表中找到两件不同的商品,它们价值的总和是最大的且不超过你的消费额度C。答案有且仅有一个。

Input:

第一行给出N个test case,对于每个test case:

第一行给出C:消费额度

第二行给出l:清单上的商品数量

第三行给出一个用空格隔开的列表,每个整数P表示一件商品的价格

Output:

对于每个test case

输出“Case #x:"之后写上两件达成条件的商品的位置,小的数在前。

Limits:

5 ≤ C ≤ 1000
1 ≤ P ≤ 1000

Sample:

Input 
Output 3
100
3
5 75 25
200
7
150 24 79 50 88 345 3
8
8
2 1 9 4 4 56 90 3
Case #1: 2 3
Case #2: 1 4
Case #3: 4 5

2.源代码:

使用简单粗暴的暴搜,算法上没有什么可说的

fin = open('A-large-practice.in', 'r')fout = open('A-large-practice.out', 'w')N = int(fin.readline())    #N test casesfor case in xrange(1, N + 1):    C = int(fin.readline())    #the amount of credit you have    l = int(fin.readline())    #the number of items in the store    P = map(int, fin.readline().strip().split()) #the price of each item    max = 0    for i in xrange(l):       #依次搜索        for j in xrange(i + 1, l):            sum = P[i] + P[j]            if sum > max and sum <= C: #找到最大且小于C时,更新最大值和两个商品的号码                max = sum                best = [i,j]    fout.write("Case #%d: %d %d \n" %(case, best[0] + 1, best[1] + 1))    #print("Case #%d: %d %d \n" %(case, best[0] + 1, best[1] + 1))fin.close()fout.close()

3,代码中几个重要函数的分析:

首先,Python中readline()函数输入的是字符串类型,为了之后的计算,需要使用int(x)来进行类型转换。

而列出商品价格的那一行就需要更多的处理,用strip()去掉头尾的空字符,spilit()来分割字符串(默认以空格为分隔符)

map(func,list)函数可以对列表中的每一个元素都执行func函数,代码中就是把每个单独的字符串都转换成整数。


xrange用法与range完全相同,所不同的是生成的不是一个数组,而是一个生成器。也就是说:

当range范围很大的时候,xrange不用开很大的内存区域也能使用。


0 0
原创粉丝点击