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

题目描述:

公司组织团建活动,其中一个游戏有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:47
import sys

m_list = [float(val) for val in sys.stdin.readline().strip().split(" ")]
total_count = [0] * 2

def 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_count2
counts = get_mypeople(0, m_list, 0,total_count)
print(counts[0] > counts[1])



  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值