1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85
| #include<bits/stdc++.h> #define int long long using namespace std; typedef pair<int, int> PII;
inline int read(){ int x = 0, f = 1; char ch = getchar(); while(ch < '0' || ch > '9') { if(ch == '-') f = -1; ch = getchar(); } while(ch >= '0' && ch <= '9') { x = x * 10 + ch - 48; ch = getchar(); } return x * f; }
const int N = 500;
void get_prime(int n, vector<int> &v){ int x = n; for(int i = 2; i <= n / i; i++){ int cnt = 0; while(x % i == 0){ cnt++; x /= i; } if(cnt) v.emplace_back(i); } if(x > 1) v.emplace_back(x); }
int dijkstra(vector<int> v, int st, int ed){ vector<int>dist(N, 0x3f3f3f3f), vis(N, 0); priority_queue<PII, vector<PII>, greater<PII>> q; dist[st] = 0; q.emplace(0, st); while(!q.empty()){ int u = q.top().second; q.pop(); if(u == ed){ return dist[u]; } if(vis[u]) continue; vis[u] = 1; for(int j = 0; j < v.size(); j++){ if(j == u) continue; int l = lcm(v[u], v[j]); if(dist[j] > dist[u] + l){ dist[j] = dist[u] + l; q.emplace(dist[j], j); } } } return -1; }
void solve(){ int a = read(), b = read(); if(a == b) { cout << 0 << '\n'; return; } vector<int> v; get_prime(a, v), get_prime(b, v); v.emplace_back(a), v.emplace_back(b), v.emplace_back(2);
sort(v.begin(), v.end()); v.erase(unique(v.begin(), v.end()), v.end()); int st, ed; for(int i = 0; i < v.size(); i++){ if(v[i] == a) st = i; else if(v[i] == b) ed = i; }
cout << dijkstra(v, st, ed) << '\n'; }
signed main(){ int t = read(); while(t--) solve(); return 0; }
|