筆試編程題彙總(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))

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章