码迷,mamicode.com
首页 > 其他好文 > 详细

F - Prime Path

时间:2018-04-29 16:29:22      阅读:161      评论:0      收藏:0      [点我收藏+]

标签:turn   sizeof   \n   namespace   code   oss   next   char   pos   

 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

标签:turn   sizeof   \n   namespace   code   oss   next   char   pos   

原文地址:https://www.cnblogs.com/jaydenouyang/p/8971074.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!