Greedy and its implementation with python

来源:互联网 发布:mac国际象棋在哪 编辑:程序博客网 时间:2024/05/14 06:46

Thesedays, I have completed some codeforces problem. Some of those problems are about greedy. What I wanna do is write something about how to use python to achieve greedy algorithm.


Let's take the example of problem 4B:

it is obviouse that the sumTime should bigger than the sum of min every mintime and smaller than the sum of max time, and first we take the minimum time every time we choose it, and save them into a heap. when the sumtime is not full, pop those item from the heap until the sumtime is full. The source code is shown as follows:


from heapq import *d, s = map(int, raw_input().split())mem = []for i in xrange(d):temp = list(map(int, raw_input().split()))mem.append(temp)sk = []s1 = 0s2 = 0h = []for i in xrange(len(mem)):s1 += mem[i][0]s2 += mem[i][1]out = ''if s >= s1 and s <= s2:print 'YES'for i, c in enumerate(mem):sk.append(c[0])s -= c[0]heappush(h, [c[1] - c[0], i])if s:while s:x, y = heappop(h)if x >= s:sk[y] += ss = 0breakelse :s -= xsk[y] += xfor i in xrange(len(sk)):out += str(sk[i])print ' '.join(out)else :for i in xrange(len(sk)):out += str(sk[i])print ' '.join(out)else :print 'NO'

Hope to help you anyway!

0 0
原创粉丝点击