思路:
bfs打表找规律
如下图
代码:
#pragma GCC optimize(2) #pragma GCC optimize(3) #pragma GCC optimize(4) #include<bits/stdc++.h> using namespace std; #define fi first #define se second #define pi acos(-1.0) #define LL long long //#define mp make_pair #define pb push_back #define ls rt<<1, l, m #define rs rt<<1|1, m+1, r #define ULL unsigned LL #define pll pair<LL, LL> #define pii pair<int, int> #define piii pair<pii, int> #define mem(a, b) memset(a, b, sizeof(a)) #define fio ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); #define fopen freopen("in.txt", "r", stdin);freopen("out.txt", "w", stout); //head int n, m; int dir[8][2] = { 2, 1, 1, 2, 2, -1, -1, 2, -2, 1, 1, -2, -2, -1, -1, -2 }; int res[5][5] = { {0, 3, 2, 3, 2}, {3, 2, 1, 2, 3}, {2, 1, 4, 3, 2}, {3, 2, 3, 2, 3}, {2, 3, 2, 3, 4} }; map<pii, bool> vis; int bfs() { queue<piii> q; q.push(piii{{0, 0}, 0}); vis.clear(); vis[pii{0, 0}] = true; while(!q.empty()) { piii now = q.front(); q.pop(); if(now.fi.fi == n && now.fi.se == m) return now.se; for (int i = 0; i < 8; i++) { int x = now.fi.fi + dir[i][0]; int y = now.fi.se + dir[i][1]; if(vis.find(pii{x, y}) == vis.end()) { vis[pii{x, y}] = true; q.push({{x, y}, now.se+1}); } } } return 0; } int main() { int T; // for (n = 0; n <= 20; n++) { // for (m = 0; m <= 20; m++) { // cout<< setw(4) << bfs(); // } // cout << endl; // } scanf("%d", &T); while(T--) { scanf("%d %d", &n, &m); n = abs(n); m = abs(m); if(n <= 4 && m <= 4) { printf("%d ", res[n][m]); continue; } if(n > m) swap(n, m); if(m <= 2*n) { printf("%d ", (m+n)/3 + (m+n)%3); } else { if(n == 0) printf("%d ", (m+2)/4*2 + m%2); else printf("%d ", (m-2*n)/4*2 + n + (m-2*n)%4); } } return 0; }