对于POJ1006的算法解决
POJ原问题网址
Description
Some people believe that there are three cycles in a person’s life that start the day he or she is born. These three cycles are the physical, emotional, and intellectual cycles, and they have periods of lengths 23, 28, and 33 days, respectively. There is one peak in each period of a cycle. At the peak of a cycle, a person performs at his or her best in the corresponding field (physical, emotional or mental). For example, if it is the mental curve, thought processes will be sharper and concentration will be easier.
Since the three cycles have different periods, the peaks of the three cycles generally occur at different times. We would like to determine when a triple peak occurs (the peaks of all three cycles occur in the same day) for any person. For each cycle, you will be given the number of days from the beginning of the current year at which one of its peaks (not necessarily the first) occurs. You will also be given a date expressed as the number of days from the beginning of the current year. You task is to determine the number of days from the given date to the next triple peak. The given date is not counted. For example, if the given date is 10 and the next triple peak occurs on day 12, the answer is 2, not 3. If a triple peak occurs on the given date, you should give the number of days to the next occurrence of a triple peak.
Input
You will be given a number of cases. The input for each case consists of one line of four integers p, e, i, and d. The values p, e, and i are the number of days from the beginning of the current year at which the physical, emotional, and intellectual cycles peak, respectively. The value d is the given date and may be smaller than any of p, e, or i. All values are non-negative and at most 365, and you may assume that a triple peak will occur within 21252 days of the given date. The end of input is indicated by a line in which p = e = i = d = -1.
Output
For each test case, print the case number followed by a message indicating the number of days to the next triple peak, in the form:
Case 1: the next triple peak occurs in 1234 days.
Use the plural form ``days’’ even if the answer is 1.
对于该问题,利用韩信点兵的方法:利用循环解决该问题,保证满足23 28,33的方式来求解。利用遍历法来尝试出该问题的实际天数。
#include <stdio.h>
void main(){
int a,b,c,d,ans,time=0;
while(scanf("%d%d%d%d",&a,&b,&c,&d)&&a!=-1){
time++;
for(ans=d+1;(ans-a)%23;ans++);
for(;(ans-b)%28;ans+=23);
for(;(ans-c)%33;ans+=23*28);
printf("Case %d: the next triple peak occurs in %d days.\n",time,ans-d);
}
}
此次收益:更加深刻的理解了,循环结构的有效率用对于程序提升时间复杂度和空间复杂度的重要性。同时 ,理解了韩信点兵的算法及其原理。
此次不足:对于问题自身前期执着于利用最大公约数****以及最小公倍数来解决该问题,这导致前期算法并不能在有效的执行时间内完成该目标。同时,自身对于韩信点兵算法的不了解也造成了对于算法自身结构生成过程中遇到了诸多麻烦。