列舉 生理週期

2021-08-13 19:29:44 字數 2407 閱讀 4226

列舉是基於逐個嘗試答案的一種問題求解策略。

#!/usr/bin/env python

# _*_ coding: utf-8 _*_

input_data = [[0, 0, 0, 0],

[0, 0, 0, 100],

[5, 20, 34, 325],

[4, 5, 6, 7],

[283, 102, 23, 320],

[203, 301, 203, 40]]

max_days = 21252

p_circle = 23

e_circle = 28

i_circle = 33

for data in input_data:

p = data[0]

e = data[1]

i = data[2]

d = data[3]

for day in xrange(d + 1, max_days + 1):

if abs(day - p) % p_circle == 0

and abs(day - e) % e_circle == 0

and abs(day - i) % i_circle == 0:

print

'the next triple peak occurs in %d days.' % (day - d)

break

the next triple peak occurs in

21252 days.

the next triple peak occurs in

21152 days.

the next triple peak occurs in

19575 days.

the next triple peak occurs in

16994 days.

the next triple peak occurs in

8910 days.

the next triple peak occurs in

10789 days.

executed in

32ms

分析:遍歷每一天,得出最終的解。

#!/usr/bin/env python

# _*_ coding: utf-8 _*_

input_data = [[0, 0, 0, 0],

[0, 0, 0, 100],

[5, 20, 34, 325],

[4, 5, 6, 7],

[283, 102, 23, 320],

[203, 301, 203, 40]]

max_days = 21252

p_circle = 23

e_circle = 28

i_circle = 33

for data in input_data:

p = data[0]

e = data[1]

i = data[2]

d = data[3]

circles = (max_days - i) // i_circle

for circle in xrange(1, circles + 1):

day = i + i_circle * circle

if (day - p) % p_circle == 0

and (day - e) % e_circle == 0:

print

'the next triple peak occurs in %d days.' % (day - d)

break

the next triple peak occurs in

21252 days.

the next triple peak occurs in

21152 days.

the next triple peak occurs in

19575 days.

the next triple peak occurs in

16994 days.

the next triple peak occurs in

8910 days.

the next triple peak occurs in

10789 days.

executed in

17ms

分析:其實中間有許多日子可以跳過。

總結:雖然列舉就是乙個個去嘗試,但在求解問題時往往不需要嘗試每乙個可能。通過一些邏輯可以合理的避免一些無用的嘗試。從時間上也可以看出時間節省了大約一半。

程式設計與演算法(二)演算法基礎

生理週期(列舉)

057 生理週期 檢視提交統計提問 總時間限制 1000ms 記憶體限制 65536kb 描述人生來就有三個生理週期,分別為體力 感情和智力週期,它們的週期長度為23天 28天和33天。每乙個週期中有一天是高峰。在高峰這天,人會在相應的方面表現出色。例如,智力週期的高峰,人會思維敏捷,精力容易高度集...

生理週期 (列舉)

生理週期 輸入 輸入四個整數 p,e,i和d。p,e,i分別表示體力 情感和 智力高峰出現的日子。d是給定的日子,可能小於p,e或 i。所有給定日子是非負的並且小於或等於365,所求的日子小於 或等於21252。輸出 從給定日子起,下一次三個高峰同一天的日子 距離給定日子 的天數 輸入樣例 0 0 ...

列舉 生理週期

題目 生理週期 人有體力 情商 智商的高峰日子,它們分別每隔23天 28天和33天出現一次。對於每個人,我們想知道何時三個高峰落在同一天。給定三個高峰出現的日子p,e和i 不一定是第一次高峰出現的日子 再給定另乙個指定的日子d,你的任務是輸出日子d之後,下一次三個高峰落在同一天的日子 用距離d的天數...