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;
    }
        
  • 相关阅读:
    JDK+Jmeter 环境搭建
    APP自动化中三大定位工具
    APP自动化环境配置
    pytest生成allure报告
    pytest怎么标记用例?
    pytest中怎么实现参数化?
    pytest中怎么引用前置中的变量
    pytest_前置后置
    toast文本提示信息元素获取
    js处理日历
  • 原文地址:https://www.cnblogs.com/tanhehe/p/3271297.html
Copyright © 2011-2022 走看看