题目:

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的更多相关文章

随机推荐

  1. java中Comparator比较器顺序问题,源码分析

    提示: 分析过程是个人的一些理解,如有不对的地方,还请大家见谅,指出错误,共同学习. 源码分析过程中由于我写的注释比较啰嗦.比较多,导致文中源代码不清晰,还请一遍参照源代码,一遍参照本文进行阅读. 原 ...

  2. C++中的内联函数分析

    1,本节课学习 C++ 中才引入的新的概念,内联函数: 2,常量与宏回顾: 1,C++ 中的 const 常量可以替代宏常数定义,如: 1,const int A = 3; <==> #d ...

  3. 58.Partition Equal Subset Sum(判断一个数组是否可以分成和相等的两个数组)

    Level:   Medium 题目描述: Given a non-empty array containing only positive integers, find if the array c ...

  4. Excel_PowerQuery——秒杀Vlookup的表合并

    终于,Power Query的第二弹来了,距离上一次PQ更博,已经将近半年. Excel_PoweQuery——条件计数.条件求和 使用PQ进行表格数据的连接合并是一件畅快的事情. 下面的数据是我随机 ...

  5. shell函数与变量

  6. go语言从例子开始之Example27.超时处理

    超时 对于一个连接外部资源,或者其它一些需要花费执行时间的操作的程序而言是很重要的.得益于通道和 select,在 Go中实现超时操作是简洁而优雅的. Example: package main im ...

  7. Kaggle数据集下载

    Kaggle数据集下载步骤: 安装Kaggle库: 注册Kaggle账户: 找到数据集,接受rules: 在My Account>>API中,点击Create New API Token, ...

  8. Es学习第四课, 倒排索引

    大家知道,ES的发明者初衷是想做一个搜索引擎给自己老婆用来搜菜谱,所以ES的核心工作就是做搜索,下面我们就开始讲关于搜索方面的知识点. DOC的概念我们第一课就讲过,它是ES存储数据的最小单元,我们再 ...

  9. Windows下Redis安装+可视化工具Redis Desktop Manager使用

    Redis是有名的NoSql数据库,一般Linux都会默认支持.但在Windows环境中,可能需要手动安装设置才能有效使用.这里就简单介绍一下Windows下Redis服务的安装方法,希望能够帮到你. ...

  10. numpy.unique

    Find the unique elements of an array. Returns the sorted unique elements of an array. There are thre ...