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:
- /*************************************** ************************************
- * Copyright (c) 2008 by Liu kaipeng *
- * Liukaipeng at gmail dot com *
- **************************************** ***********************************/
- /* @ Judge_id 00000 846 C ++ "Steps "*/
- # Include <algorithm>
- # Include <cmath>
- # Include <cstdio>
- # Include <cstring>
- # Include <deque>
- # Include <fstream>
- # Include <iostream>
- # Include <list>
- # Include <map>
- # Include <queue>
- # Include <set>
- # Include <stack>
- # Include <string>
- # Include <vector>
- Using namespace STD;
- /*
- * 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 ).
- */
- Int steps (INT Dist)
- {
- If (Dist = 0) return 0;
- Int step = SQRT (DIST );
- If (Step * step = DIST) step = Step * 2-1;
- Else if (Step * Step + step <Dist) step = Step * 2 + 1;
- Else step = Step * 2;
- Return step;
- }
- Int main (INT argc, char * argv [])
- {
- # Ifndef online_judge
- Freopen (string (argv [0]) + ". In"). c_str (), "r", stdin );
- Freopen (string (argv [0]) + ". Out"). c_str (), "W", stdout );
- # Endif
- Int ncases;
- Cin> ncases;
- For (int x, Y; ncases> 0 & CIN> x> Y; -- ncases)
- Cout <steps (Y-x) <'/N ';
- Return 0;
- }