首页 > ACM题库 > HDU-杭电 > HDU 1049 Climbing Worm[解题报告] C++
2013
11-26

HDU 1049 Climbing Worm[解题报告] C++

Climbing Worm

问题描述 :

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.

输入:

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.

输出:

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.

样例输入:

10 2 1
20 3 1
0 0 0

样例输出:

17
19

#include <iostream>
using namespace std;

int n,u,d;

int height;
int _time;
int main()
{
    while(cin>>n>>u>>d)
    {
         if((n&&u&&d)==0)
             break;
         height = 0;
         _time = 0;
         while(height < n)
         {
             height += u;
             _time++;
             if(height >= n)
             {
                  cout<<_time<<endl;
                  break;
             }
             height -= d;
             _time++;
         }
    }
    return 0;
}


  1. #include <cstdio>

    int main() {
    //answer must be odd
    int n, u, d;
    while(scanf("%d%d%d",&n,&u,&d)==3 && n>0) {
    if(n<=u) { puts("1"); continue; }
    n-=u; u-=d; n+=u-1; n/=u;
    n<<=1, ++n;
    printf("%dn",n);
    }
    return 0;
    }

  2. 我还有个问题想请教一下,就是感觉对于新手来说,递归理解起来有些困难,不知有没有什么好的方法或者什么好的建议?

  3. 第二个方法挺不错。NewHead代表新的头节点,通过递归找到最后一个节点之后,就把这个节点赋给NewHead,然后一直返回返回,中途这个值是没有变化的,一边返回一边把相应的指针方向颠倒,最后结束时返回新的头节点到主函数。