不管你是怎么做的,反正我是用二分做的,相当于做了一个预处理。一个最优的序列一定是 1 2 3 .. N .. 3 2 1,或者是 1 2 3 .. N N .. 3 2 1.
代码如下:
#include <cstdlib> #include <cstdio> using namespace std; long long rec[131100], a, b; void pre() { rec[1] = 1; long long LIM = 1LL << 32, base = 1; int i; for (i = 2; rec[i-1] <= LIM; ++i) { rec[i] = rec[i-1] + base; if (!(i & 1)) base++; } } int bsearch(int l, int r, long long val) { int mid, ret; while (l <= r) { mid = (l + r) >> 1; if (rec[mid] > val) { ret = mid; r = mid - 1; } else if (rec[mid] < val) { l = mid + 1; } else { ret = mid; break; } } return ret; } int main() { pre(); int T; scanf("%d", &T); while (T--) { scanf("%I64d %I64d", &a, &b); if (a == b) { puts("0"); continue; } printf("%d\n", bsearch(1, 131072, b-a)); } return 0; }