UV problem solution: 846-steps

Source: Internet
Author: User

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. * Let F (n) denote the furthest distance we can go with n steps, then we can
  23. * Derive this formula easily:
  24. * F (n) = (n + 1)/2) ^ 2 if n is odd, (1, 2, 3, 4, 3, 2, 1)
  25. * F (n) = (n/2) ^ 2 + n/2 If n is even. (1, 2, 3, 3, 2, 1)
  26. * Give the distance of F (N), we can find N by looking around the square root
  27. * Of F (n ).
  28. */
  29. Int steps (INT Dist)
  30. {
  31. If (Dist = 0) return 0;
  32. Int step = SQRT (DIST );
  33. If (Step * step = DIST) step = Step * 2-1;
  34. Else if (Step * Step + step <Dist) step = Step * 2 + 1;
  35. Else step = Step * 2;
  36. Return step;
  37. }
  38. Int main (INT argc, char * argv [])
  39. {
  40. # Ifndef online_judge
  41. Freopen (string (argv [0]) + ". In"). c_str (), "r", stdin );
  42. Freopen (string (argv [0]) + ". Out"). c_str (), "W", stdout );
  43. # Endif
  44. Int ncases;
  45. Cin> ncases;
  46. For (int x, Y; ncases> 0 & CIN> x> Y; -- ncases)
  47. Cout <steps (Y-x) <'/N ';
  48. Return 0;
  49. }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.