HDU 1049 Climbing Worm

Problem Description
An inch worm is at the bottom of a well n inches deep. It has enough energy to climb u inches every minute, but then has to rest a minute before climbing again. During the rest, it slips down d inches. The process of climbing and resting then repeats. How long before the worm climbs out of the well? We'll always count a portion of a minute as a whole minute and if the worm just reaches the top of the well at the end of its climbing, we'll assume the worm makes it out.
 

 

Input
There will be multiple problem instances. Each line will contain 3 positive integers n, u and d. These give the values mentioned in the paragraph above. Furthermore, you may assume d < u and n < 100. A value of n = 0 indicates end of output.
 

 

Output
Each input instance should generate a single integer on a line, indicating the number of minutes it takes for the worm to climb out of the well.
 

 

Sample Input
10 2 1 20 3 1 0 0 0
 

 

Sample Output
17 19
 
题意:总深n英寸,每秒向上爬u英寸,爬一秒后休息一秒,休息时每秒下滑的英寸。
分析:
     解法一--简单的用两个while循环。
AC源代码(C语言):
 1 #include<stdio.h>
 2 int main()
 3 {
 4   int a,b,c,i,s;
 5   while(1)
 6   {
 7     s=0;i=0;
 8     scanf("%d%d%d",&a,&b,&c);
 9     if(a==0&&b==0&&c==0)  break;
10     while(1)
11     {
12       s+=b;
13       i++;
14       if(s>=a) break;//要设定成s>=a,而不能设定成s==a; 
15       else
16       {
17         s-=c;
18         i++;         
19       }                    
20     }      
21     printf("%d\n",i);             
22   }
23   return 0;    
24 }

     解法二--整体分析,每秒上升u,下降d,相当于每秒上升(u-d)。注意一开始要减去u,即n-u。本题之所以可以用这种方法是因为输入的n,u,d都是整数,不存在最后输出的时间不是整数是情况!

AC源代码(C语言):

 1 #include<stdio.h>
 2 int main()
 3 {    
 4     int n,u,d;
 5     while(scanf("%d%d%d",&n,&u,&d),n) 
 6        {        
 7            int t=(n-u)/(u-d);
 8            if(t*(u-d)<(n-u)) 
 9               t++; 
10            t*=2;     
11            t++;
12            printf("%d\n",t);  
13        }     
14     return 0;
15 }   

 

 2013-01-13
posted @ 2013-01-13 20:36  刘一卜  阅读(451)  评论(0编辑  收藏  举报