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;
- }