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:
InputOutput
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不用开很大的内存区域也能使用。
- Code Jam - Store Credit for Python
- Google code jam: Problem A. Store Credit
- Google Code Jam Notes - Store Credit - Java
- (code jam)Problem A. Store Credit
- 【Google Code Jam】Problem A. Store Credit
- Store Credit-GOOGLE CODE JAM AFICA 2010 Qualification Round
- [C++]Store Credit——Google Code Jam Qualification Round Africa 2010
- Code Jam - Reverse Words for Python
- Code Jam - Minimum Scalar Product for Python
- Code Jam to I/O for Women 2016【上】
- caffe for python code
- hdu 5619 Jam's store
- Google Code Jam 2006
- Google China Code Jam
- code.jam - pixelcanvas
- code.jam - egg drops
- Google Code Jam
- [Code Jam] Alien Language
- 三种对象初始化代码,有何不同求解答
- 派生类到基类转换的可访问性——新解
- 60 谁获得了最高奖学金
- HDU4870:Rating(DP)
- mysql数据库迁移
- Code Jam - Store Credit for Python
- VPN寻址及路由
- struts2 全局拦截器,显示请求方法和参数
- 62 笨小熊
- 字典树模板及讲解 http://www.cnblogs.com/tanky_woo/archive/2010/09/24/1833717.html
- hdu-1071-The area
- ok6410学习之触摸屏篇
- 并查集
- iphone判断当前网络连接类型WIF、WWAN、2G和3G