枚举——生理周期

文章作者:Tyan
博客:noahsnail.com  |  CSDN  |  简书

1. 枚举

枚举是基于逐个尝试答案的一种问题求解策略。

2. 生理周期

  • 问题描述
    人有体力、情商、智商的高峰日子,它们分别每隔23天、28天和33天出现一次。对于每个人,我们想知道何时三个高峰落在同一天。给定三个高峰出现的日子p,e和i(不一定是第一次高峰出现的日子),再给定另一个指定的日子d,你的任务是输出日子d之后,下一次三个高峰落在同一天的日子(用距离d的天数表示)。例如:给定日子为10,下次出现三个高峰同一天的日子是12,则输出2。

  • 输入
    输入四个整数:p,e,i和d。p,e,i分别表示体力、情感和智力高峰出现的日子。d是给定的日子,可能小于p,e或i。所有给定日子是非负的并且小于或等于365,所求的日子小于或等于21252。

  • 输出
    从给定日子起,下一次三个高峰同一天的日子(距离给定日子的天数)。

  • 输入样例
    0 0 0 0
    0 0 0 100
    5 20 34 325
    4 5 6 7
    283 102 23 320
    203 301 203 40
    -1 -1 -1 -1
    四个-1表示输入结果,四个数字分别表示p,e,i,d。

  • 输出样例
    Case 1: the next triple peak occurs in 21252 days.
    Case 2: the next triple peak occurs in 21152 days.
    Case 3: the next triple peak occurs in 19575 days.
    Case 4: the next triple peak occurs in 16994 days.
    Case 5: the next triple peak occurs in 8910 days.
    Case 6: the next triple peak occurs in 10789 days.

  • 解法一
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#!/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
  • 输出
1
2
3
4
5
6
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.
  • 用时
1
executed in 32ms

分析:遍历每一天,得出最终的解。

  • 方法二
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#!/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
  • 输出
1
2
3
4
5
6
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.
  • 用时
1
executed in 17ms

分析:其实中间有许多日子可以跳过。

总结:虽然枚举就是一个个去尝试,但在求解问题时往往不需要尝试每一个可能。通过一些逻辑可以合理的避免一些无用的尝试。从时间上也可以看出时间节省了大约一半。

源码地址:https://github.com/SnailTyan/programming-and-algorithms/blob/master/physical_period.py,记得给个star。

参考资料

  1. 程序设计与算法(二)算法基础
如果有收获,可以请我喝杯咖啡!