UVa Problem Solution: 846 - Steps


Let f(n) denote the furthest distance we can go with n steps, then we can derive this formula easily:
   f(n) = ((n+1)/2)^2 if n is odd, (1, 2, 3, 4, 3, ,2, 1)
   f(n) = (n/2)^2 + n/2 if n is even. (1, 2, 3, 3, 2, 1)
Give the distance of f(n), we can find n by looking around the square root of f(n).

Code:
  1. /***************************************************************************
  2.  *   Copyright (C) 2008 by Liu Kaipeng                                     *
  3.  *   LiuKaipeng at gmail dot com                                           *
  4.  ***************************************************************************/
  5. /* @JUDGE_ID 00000 846 C++ "Steps" */
  6. #include <algorithm>
  7. #include <cmath>
  8. #include <cstdio>
  9. #include <cstring>
  10. #include <deque>
  11. #include <fstream>
  12. #include <iostream>
  13. #include <list>
  14. #include <map>
  15. #include <queue>
  16. #include <set>
  17. #include <stack>
  18. #include <string>
  19. #include <vector>
  20. using namespace std;
  21.      
  22. /*
  23.  * Let f(n) denote the furthest distance we can go with n steps, then we can
  24.  * derive this formula easily:
  25.  *   f(n) = ((n+1)/2)^2 if n is odd, (1, 2, 3, 4, 3, ,2, 1) 
  26.  *   f(n) = (n/2)^2 + n/2 if n is even. (1, 2, 3, 3, 2, 1)
  27.  * Give the distance of f(n), we can find n by looking around the square root 
  28.  * of f(n).
  29.  */
  30. int steps(int dist)
  31. {
  32.   if (dist == 0) return 0;
  33.   int step = sqrt(dist);
  34.   if (step * step == dist) step = step * 2 - 1;
  35.   else if (step * step + step < dist) step = step * 2 + 1;
  36.   else step = step * 2;
  37.   return step;
  38. }
  39.           
  40. int main(int argc, char *argv[])
  41. {
  42. #ifndef ONLINE_JUDGE
  43.   freopen((string(argv[0]) + ".in").c_str(), "r", stdin);
  44.   freopen((string(argv[0]) + ".out").c_str(), "w", stdout);
  45. #endif
  46.   int ncases;
  47.   cin >> ncases;
  48.   for (int x, y; ncases > 0 && cin >> x >> y; --ncases)
  49.     cout << steps(y - x) << '/n';
  50.   return 0;
  51. }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值