笔试编程题汇总(4)


"""
description:
    given a music set, select a pair of musics 
    and the sum of these two musics's duration is right minutes (divisible by 60)
example 1:
    input:
        [20 40 60]
    output:
        1
    (20,40)
example 2:
    input:
        [20 40 60 120]
    output:
        2
    (20,40),(60,120)
"""

"""
基本思想:
    这是一个有限的组合匹配问题,暴力搜索的复杂度是O(n^2),使用直方图统计每一个长度的音乐的个数,然后进行组合,注意长度为60的倍数的音乐和长度为30的音乐要特殊处理,负责度是O(n)
"""
import sys



playlist=[20, 40, 60, 60, 120, 30, 30, 30, 60, 29, 31, 28, 32, 1, 59]

def get_num(playlist):
    hist = [int(0)]*60
    for data in playlist:
        hist[int(data%60)] += 1
    num = int(0)
    for idx in range(30-1):
        num += hist[idx+1]*hist[59-idx]  #29
    num += hist[30]*(hist[30]-1)/2 + hist[0]*(hist[0]-1)/2
    return int(num)

if __name__ == "__main__":
    playlist = eval(sys.stdin.readline().strip())
    print(get_num(playlist))

你可能感兴趣的:(Python,算法,算法,python,笔试)