递归--A,B选同事,每次选1或2个,判断A是否胜利

来源:互联网 发布:增视能弱视训练软件 编辑:程序博客网 时间:2024/05/17 01:17

题目描述:

公司组织团建活动,其中一个游戏有A、B两名参赛者参加,游戏规则如下:有m个不同身高的同事站成一排,A、B两个参赛者依次从左到右选择一名或者两名同时出列(A先开始),直到所有同时都被选择完位置,最终计算两名参赛者所选同事的身高总和,如果A选的同时身高综合大于B,则A胜利,否则,B胜利。

输入:同时身高序列,以空格分割

输出:A胜利则True,否则False


Python代码实现:

#!/usr/bin/env python# -*- coding:utf-8 -*- # @Author:lthan# @Email :xiaohan809@qq.com# @Time  :2017/9/13 21:47import sysm_list = [float(val) for val in sys.stdin.readline().strip().split(" ")]total_count = [0] * 2def get_mypeople(index, m_list,which,total_count):    #轮到自己的时候每个人都很贪婪,如果剩余员工少于2个,全部带走    if len(m_list) <= index + 2:        for i in range(index,len(m_list)):            total_count[which] += m_list[i]        return total_count    else:        # 拿一个        total_count1 = total_count[:]        total_count1[which] += m_list[index]        total_count1 = get_mypeople(index+1,m_list,(which+1)%2,total_count1)        #拿两个        total_count2 = total_count[:]        total_count2[which] += m_list[index]        total_count2[which] += m_list[index+1]        total_count2 = get_mypeople(index+2,m_list,(which+1)%2,total_count2)        #取最终最大的那个拿法        if total_count1[which] > total_count2[which]:            return total_count1        else:            return total_count2counts = get_mypeople(0, m_list, 0,total_count)print(counts[0] > counts[1])



阅读全文
0 0
原创粉丝点击