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;
    }
        
  • 相关阅读:
    jetty插件配置
    连接Oracle时ORA-12541 TNS 无监听程序
    查看表结构
    判断时间差,返回1或2或3
    template_共享模板
    template_showpost
    template_homepage
    tensorflow解决Fizz Buzz 的问题
    神经网络——项目二CNN手写数字识别
    神经网络——项目一 手写数字识别
  • 原文地址:https://www.cnblogs.com/tanhehe/p/3271297.html
Copyright © 2011-2022 走看看