F - Prime Path
Posted jaydenouyang
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了F - Prime Path相关的知识,希望对你有一定的参考价值。
1 #include <iostream> 2 #include <queue> 3 #include <cstdio> 4 #include <cstring> 5 using namespace std; 6 7 struct node{ 8 int cur, step; 9 }now, Next; 10 int vis[10001], star, finish, prime[10001] = { 0, 0, 1 }; 11 12 void init(){ 13 for (int i = 2; i < 10001; i++){ 14 if (!prime[i]){ 15 for (int j = 2; i*j < 10001; j++) 16 prime[i*j] = 1; 17 } 18 } 19 } 20 21 int bfs(){ 22 queue<node> Q; 23 vis[star] = 1; 24 now.cur = star, now.step = 0; 25 Q.push(now); 26 while (!Q.empty()){ 27 int i, j; 28 char num[5]; 29 now = Q.front(); 30 Q.pop(); 31 if (now.cur == finish) return now.step; 32 for (i = 0; i < 4; i++){ 33 sprintf(num, "%d", now.cur); 34 for (j = 0; j < 10; j++){ 35 if (j == 0 && i == 0) 36 continue; 37 if (i == 0) 38 Next.cur = j * 1000 + (num[1] - ‘0‘) * 100 + (num[2] - ‘0‘) * 10 + (num[3] - ‘0‘); 39 else if (i == 1) 40 Next.cur = j * 100 + (num[0] - ‘0‘) * 1000 + (num[2] - ‘0‘) * 10 + (num[3] - ‘0‘); 41 else if (i == 2) 42 Next.cur = j * 10 + (num[0] - ‘0‘) * 1000 + (num[1] - ‘0‘) * 100 + (num[3] - ‘0‘); 43 else if (i == 3) 44 Next.cur = j + (num[0] - ‘0‘) * 1000 + (num[1] - ‘0‘) * 100 + (num[2] - ‘0‘) * 10; 45 if (!prime[Next.cur] && !vis[Next.cur]) 46 { 47 Next.step = now.step + 1; 48 vis[Next.cur] = 1; 49 Q.push(Next); 50 } 51 } 52 } 53 } 54 return -1; 55 } 56 57 int main(){ 58 int t, ans; 59 cin >> t; 60 init(); 61 while (t--){ 62 cin >> star >> finish; 63 memset(vis, 0, sizeof(vis)); 64 ans = bfs(); 65 if (ans == -1) cout << "Impossible\n"; 66 else cout << ans << endl; 67 } 68 return 0; 69 }
以上是关于F - Prime Path的主要内容,如果未能解决你的问题,请参考以下文章