题目网址: 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