題目網址: POJ -- 3126ios
給出變化規律,問最少變化幾回。使用寬搜就能夠解決,每一個數的出度是40。spa
這道題目還用到了簡單的素數斷定,四位數不大,判斷一個四位數是不是素數只要O(100)的複雜度就夠了(最大數不超過10000)。code
一個小技巧是將每次變化出來的新數都作上標記,若是是素數就進隊,不是素數下次遇到也不用再花時間去斷定了。ci
#include <cstdio> #include <queue> #include <iostream> #include <cstring> using namespace std; queue<int> q; const int maxn = 10010; int dis[maxn]; int vis[maxn]; bool judge(int n) { for(int i = 2; i*i <= n; i++) { if(!(n % i)) return false; } return true; } int main() { int a, b; int T; cin >> T; while(T--) { memset(vis, 0, sizeof(vis)); memset(dis, -1, sizeof(dis)); while(!q.empty()) q.pop(); scanf("%d%d", &a, &b); q.push(a); dis[a] = 0; vis[a] = 1; while(!q.empty()) { int x = q.front(); q.pop(); if(x == b) { printf("%d\n", dis[x]); break; } int X[5], x_ = x; X[1] = x_ % 10; x_ /= 10; X[2] = x_ % 10; x_ /= 10; X[3] = x_ % 10; x_ /= 10; X[4] = x_ % 10; x_ /= 10; for(int i = 1; i <= 4; i++) { for(int k = 0; k <= 9; k++) { int y = 0; if(i != 1) y += X[1]; else y += k; if(i != 2) y += X[2] * 10; else y += k * 10; if(i != 3) y += X[3] *100; else y += k * 100; if(i != 4) y += X[4] *1000; else y += k * 1000; if(y >= 1000 && !vis[y]) { vis[y] = 1; if(judge(y)) { q.push(y); dis[y] = dis[x] + 1; } } } } } } return 0; }
把四位數剝離出來再重組的過程是挺噁心的。。。get