zoukankan      html  css  js  c++  java
  • POJ3126 Prime Path(BFS)

    题目链接

    AC代码如下:

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <cstdlib>
    #include <string>
    #include <queue>
    #include <algorithm>
    #include <map>
    #include <ctype.h>
    
    using namespace std;
    
    const int maxn = 10000;
    
    struct node {
        int x, s;
    };
    
    int end;
    bool vis[maxn], prime[maxn];
    
    int BFS(int s) {
        
        if(s == end) return 0;
        
        queue<node> Q;
        memset(vis, 0, sizeof(vis));
    
        vis[s] = true;
        Q.push((node){s, 0});
    
        while(!Q.empty()) {
          node e = Q.front(); Q.pop();
          for(int i=1; i<=1000; i *= 10) {
              for(int j=0; j<10; j++) {
                if(i == 1000 && j == 0) continue;
                int t = e.x%i+j*i+e.x/(i*10)*(i*10);
                if(t == end) return e.s+1;
                if(prime[t]) {
                    if(vis[t]) continue;
                    vis[t] = true;
                    Q.push((node){t, e.s+1});
                }
              }
          }  
        }
        return -1;
    }
        
    
    int main() {
        int T, s;
        scanf("%d", &T);
    
        memset(prime, true, sizeof(prime));
        prime[0] = prime[1] = false;
    
        for(int i=2; i*i<maxn; i++) {
          if(prime[i])
            for(int j=i*i; j<maxn; j += i) {
                prime[j] = false;
            }
        }
    
        
        while(T--) {
          scanf("%d%d", &s, &end);
          printf("%d
    ", BFS(s));
        }
    
        return 0;
    }
        
  • 相关阅读:
    友链
    Vue打包后处理跨域
    es6 Promise
    express get和post数据
    Nodejs登陆注册应用
    bootstrap按钮
    vue-router
    vue--transition多个元素运动
    $ git push -u origin masterremote时出现错误: error: GH007: Your push would publish a private email address.
    vue.js监听
  • 原文地址:https://www.cnblogs.com/tanhehe/p/3271297.html
Copyright © 2011-2022 走看看