题意为给出两个四位素数A、B,每次只能对A的某一位数字进行修改,使它成为另一个四位的素数,问最少经过多少操作,能使A变到B。可以直接进行BFS搜索
1 #include<bits/stdc++.h> 2 using namespace std; 3 4 bool isPrime(int n){//素数判断 5 if(n == 2 || n == 3) return true; 6 else{ 7 int k = sqrt(n) + 1; 8 for(int i = 2; i < k; i++){ 9 if(n % i == 0) return false; 10 } 11 return true; 12 } 13 } 14 15 bool Prime[10010]; 16 int visit[10010]; 17 void getPrime(){ 18 for(int i = 1000; i < 10000; i++){ 19 if(isPrime(i))Prime[i] = true; 20 } 21 } 22 23 struct Node{ 24 int num;//储存数字 25 int cost;//操作步数 26 }; 27 28 Node bfs(int start, int end){ 29 queue<Node> q; 30 Node front; 31 front.num = start; 32 front.cost = 0; 33 visit[start] = 1; 34 q.push(front); 35 while(!q.empty()){ 36 front = q.front(); q.pop(); 37 38 for(int i = 1; i < 10; i++){//换千位 39 int m = front.num; 40 m = m % 1000 + i * 1000; 41 if(!visit[m] && Prime[m]){ 42 visit[m] = 1; 43 Node tmp = front; 44 tmp.num = m; 45 tmp.cost++; 46 q.push(tmp); 47 48 if(m == end)return tmp; 49 } 50 } 51 52 for(int i = 0; i < 10; i++){//换百位 53 int m = front.num; 54 m = m % 100 + (m/1000) * 1000 + i * 100; 55 if(!visit[m] && Prime[m]){ 56 visit[m] = 1; 57 Node tmp = front; 58 tmp.num = m; 59 tmp.cost++; 60 q.push(tmp); 61 62 if(m == end)return tmp; 63 } 64 } 65 66 for(int i = 0; i < 10; i++){//换十位 67 int m = front.num; 68 m = m % 10 + (m/100) * 100 + i * 10; 69 if(!visit[m] && Prime[m]){ 70 visit[m] = 1; 71 Node tmp = front; 72 tmp.num = m; 73 tmp.cost++; 74 q.push(tmp); 75 if(m == end)return tmp; 76 } 77 } 78 79 for(int i = 0; i < 10; i++){//换个位 80 int m = front.num; 81 m = (m/10) * 10 + i; 82 if(!visit[m] && Prime[m]){ 83 visit[m] = 1; 84 Node tmp = front; 85 tmp.num = m; 86 tmp.cost++; 87 q.push(tmp); 88 89 if(m == end)return tmp; 90 } 91 } 92 } 93 Node tmp; 94 tmp.num = 0; 95 tmp.cost = 0; 96 return tmp; 97 } 98 int main(){ 99 int n; 100 cin >> n; 101 getPrime(); 102 while(n--){ 103 int a, b; 104 cin >> a >> b; 105 Node tmp; 106 memset(visit, 0, sizeof(visit)); 107 tmp = bfs(a, b); 108 if(tmp.num == 0 && tmp.cost == 0) cout << 0 << endl; 109 else{ 110 cout << tmp.cost << endl; 111 } 112 } 113 }