ACM_ICPC_Team
题目:
There are a number of people who will be attending ACM-ICPC World Finals. Each of them may be well versed in a number of topics. Given a list of topics known by each attendee, you must determine the maximum number of topics a 2-person team can know. Also find out how many ways a team can be formed to know that many topics. Lists will be in the form of bit strings, where each string represents an attendee and each position in that string represents a field of knowledge, 1 if its a known field or 0 if not.
附上链接:ACM_ICPC_Team
初步想法
这题我初见想到的就是简单的三次循环遍历
for i in range(n):
for j in range(i + 1, n):
for k in range(m):
# 进行判断及计数等操作
虽然功能上一定可以实现,但是时间复杂度达到了O(n^2 * m)的地步,这显然不能满足要求
进阶解决
为了避免嵌套循环大量消耗时间,我改用itertools库中的combinations(list, num)函数,该函数可以根据给定的参数完成对给定列表的全组合,即数学上的C(num, len(list)),结果返回一个包含全部全组合的元组,于是最外层的两个循环备修改为如下代码:
for i in itertools.combinations(topic, 2):
即将列表topic中的每两个元素分别组合形成一个新元组,并对其进行遍历,就实现了之前的那两个外层循环同样的功能
而后对第三个循环的思考中我发现:
题目中已经给定的主函数中,传入的变量是一个元素为字符串形式的列表,而不是数值形式
这就又为我们解题提供了方便,将两者进行或操作并判断1的个数就简化为了下面这一句话:
count = str(bin(int(i[0], 2) | int(i[1], 2))).count('1')
其中int(***, 2)中的第二个参数2表示将字符串转换为二进制数字
最终程序
简化了上面的问题,这个题目也就没有难点了,下面附上我最终通过的代码
def acmTeam(topic):
combine = itertools.combinations(topic, 2)
max_num = 0
num = 1
for i in combine:
res = str(bin(int(i[0], 2) | int(i[1], 2)))
count = res.count('1')
if count > max_num:
max_num = count
num = 1
elif count == max_num:
num += 1
return max_num, num
ACM_ICPC_Team的更多相关文章
随机推荐
- 这么简单的 Redis 面试题都不懂,怎么拿offer?
来源:mp.weixin.qq.com/s/daBkliC8dAT_zYyoLiS7WA 随着系统访问量的提高,复杂度的提升,响应性能成为一个重点的关注点.而缓存的使用成为一个重点.redis 作为缓 ...
- 插件化框架解读之Class文件与Dex文件的结构(一)
阿里P7移动互联网架构师进阶视频(每日更新中)免费学习请点击:https://space.bilibili.com/474380680 Class文件 Class文件是Java虚拟机定义并被其所识别的 ...
- kubernetes容器集群自签TLS证书
集群部署 1.环境规划 2.安装docker 3.自签TLS证书 4.部署Flannel网络 5.部署Etcd集群 6.创建Node节点kubeconfig文件 7.获取K8S二进制包 8.运行Mas ...
- js常用转义字符列表
转义字符 含义 \n 换行 \t 制表符 \b 空格 \r 回车 \f 换页符 \ 反斜杠 ' 单引号 '' 双引号 \0nnn 八进制代码 nnn 表示的字符( n 是 0 到 7 中的一个八进制数 ...
- 致命错误: Call to undefined function %y-%M-%d()
在TP5.0中套模板时出现的问题: 原有html模板代码: <input type="text" onfocus="WdatePicker({ maxDate:'# ...
- while/until/for 循环举例2
- go语言从例子开始之Example5.for循环
for 是 Go 中唯一的循环结构.这里有 for 循环的三个基本使用方式. package main import "fmt" func main() { 最常用的方式,带单个循 ...
- Thinkphp5.0 自定义命令command的使用
在app下的command文件中,定义命令所在的模块以及命名. 然后保存,打开cmd,php think 定义的那个command的名字,完整的命令行为:php think clearInvalidO ...
- Yum与RPM
Yum(全称为 Yellow dog Updater, Modified)是一个在Fedora和RedHat以及CentOS中的Shell前端软件包管理器.基于RPM包管理,能够从指定的服务器自动下载 ...
- windows系统下MySQL中遇到1045问题
报错内容为"1045 Access denied for user 'root'@'localhost' (using password:YES)",对应的原因是密码错误,如 ...