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
- Greedy and its implementation with python
- Shell sort and its implementation
- Selection sort and its implementation
- Bubble sort and its implementation
- The implementation of anonymous methods in C# and its consequences
- MST implementation with Kruskal and Boruvka algorithm
- Stack ---- Implementation in C and Python
- Seminar《Fast Random Walk with Restart and Its Applications》
- Matrix Factorization: A Simple Tutorial and Implementation in Python
- Matrix Factorization: A Simple Tutorial and Implementation in Python
- Matrix Factorization: A Simple Tutorial and Implementation in Python
- Using FANN and its Python bindings to construct neural networks
- Tcp/Ip: Architcture, Protocols, and Implementation With Ipv6 and Ip Security
- spinlock implementation with arm
- Python and cryptography with pycrypto
- Python之 with and as
- Algorithms Collection and Implementation
- EFLAGS description and implementation
- android学习之ListView如何使用
- ./release_codes.sh release_${prjname}.cfg $2 || exit 1(||是什么意思)
- [C++对象模型][7]单继承与虚函数表
- ActiveReports 报表应用教程 (2)---清单类报表
- 从数据库中取数据vo接收后展示出现的问题
- Greedy and its implementation with python
- nodejs在centos下的安装
- Opencv学习笔记——普通坐标转化为极坐标
- MEID校验位算法
- C++ Unicode SBCS 函数对照表
- Thread.currentThread().getContextClassLoader()与Test.class.getClassLoader()区别
- 獲取當前日期往前推三個月(當前日期減去三個月)
- ActiveReports 报表应用教程 (3)---图表报表
- SSH三大框架一些异常的办法