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的更多相关文章
随机推荐
- 【题解】A Horrible Poem
题目大意 给出一个由小写英文字母组成的字符串 S,再给出 q 个询问,要求回答 S 某个子串的最短循环节. 如果字符串 B 是字符串 A 的循环节,那么 A 可以由 B 重复若干次得到. 输入格式 第 ...
- Logstash,Fluentd, Logtail对比伤害
摘要: 针对主流日志采集客户端(Logstash,Fluentd,以及日志服务客户端Logtail)进行功能.性能和稳定性测评 日志收集的场景 DT时代,数以亿万计的服务器.移动终端.网络设备每天产生 ...
- Linux上用sublime编辑Python时候出现"SyntaxError: Non-ASCII character ‘\xe5′ in file"的问题
Reopen with Encoding UTF-8也没用,那只是在编辑界面里面显示出中文而已,编译的时候还是不能识别中文. 所以,还是按网上说的吧,在每一个有中文的文件第一行加上# -*- codi ...
- 45.Sort List(链表排序)
Level: Medium 题目描述: Sort a linked list in O(n log n) time using constant space complexity. Example ...
- 图片查看器(类似于QQ,另外又加了JARA的下方的图片缩略导航图)
源码地址:https://gitee.com/yolanda624/coffer/tree/master/src/components/a-photo-view
- GIT 的常见用法
git init 新建代码库 git clone新建项目 git branch 查看分支 git config 显示配置 git config -e 显示配置文件 git config user.na ...
- Freemarker模板和依赖
<html> <head> <meta charset="utf-8"> <title>Freemarker入门小DEMO < ...
- 03-树2 List Leaves(25 分)
Given a tree, you are supposed to list all the leaves in the order of top down, and left to right. I ...
- Monkey学习
Monkey是一个工程,生成伟随机事件流(在一段时间内完全不重复的事件流),由种子生成.可以模拟用户,点击,触屏等.最好用来做压力测试.无法做功能测试. adb shell monkey -p -v ...
- HTML—学习笔记
1 .表格 <br/>换行 <p> align top<img src="./julizi.png" align="top" &g ...