阿里18秋招在线测验题-射击场

题目要求:

 * 题目:假设靶场有n个靶子,n个靶子的分数为数组score[n],score[i]为0的靶子不能射击。
 * 射中第i个靶子的,假如第i个靶子的左右两边均有相邻靶子,则射中第i个靶的得分为score[left]*score[i]*score[right]
 * 并且射中之后,score[left]和score[right]变为相邻的两个靶子。
 * 当射中的靶子右边没有相邻的靶子则得分为score[left]*score[i];左边同理。
 * 若左右两边均没有靶子,则得分为score[i]

 * 求最多能得多少分?

Python3 实现(贪心思想

# @Time   :2018/5/11
# @Author :Yinxing
# 解题思路 贪心算法
# 每次选择得分最高的那个点,条件是,如果存在得分最高且相同的数值,则优先选择靶牌数值最小的那个

def Target(tar):
    n = len(tar)
    if n==1: return tar[0]
    elif n==0: return None
    get_score, score = [-1] * n, 0  # 记录本次
    while n > 0:
        tmp_tar = [1] + tar + [1]  # 添加首尾,方便计算
        for i in range(1, n + 1):  # 记录现在每个靶得分情况
            get_score[i-1] = tmp_tar[i - 1] * tmp_tar[i] * tmp_tar[i + 1]

        # 获取最优的打靶点
        index, max_score, tmp_score = 0, 0, 0  # index:最佳打靶位置,max_score:当前最高得分,tmp_score:当前靶子上的分值
        for i in range(n):  # 选择最高得分,或者最高得分相同,选择靶子上的分值最小的那个
            if max_score < get_score[i] or (max_score == get_score[i] and tar[i] < tmp_score):
                max_score, tmp_score, index = get_score[i], tar[i], i

        if get_score[index] > 0:
            score += get_score[index]  # 获取最大值
            del tar[index]  # 已经打过的靶,删除掉
            n = len(tar)  # 更新长度
            get_score = [-1] * n  # 重新初始化得分数组
        else:  # 最佳打靶位置小于等于0,则说明没有打靶位置,结束
            break
    return score


if __name__ == '__main__':
    tar = [2, 4, 5, 6, 3, 2]
    tar = [2, 4, 5, 0, 3, 2]
    tar = [9, 1, 1, 1, 1, 9]
    print('靶子分值:', tar)
    out = Target(tar)
    print('最高得分:',out)
发现问题,可以留言指教哦。小白一个。

猜你喜欢

转载自blog.csdn.net/xx_123_1_rj/article/details/80279584
今日推荐