• POJ 3126


    #include<iostream>
    #include<queue>
    #include<string>
    using namespace std;
    
    const int M = 10000;
    int prime[M],pn;
    bool notprime[M];
    
    void init()
    {
    	pn = 0;
    	notprime[1] = 1;
    	for(int i = 2; i < M; i++)
    	{
    		if(notprime[i] == 0)
    			prime[pn++] = i;
    		for(int j = 0; j < pn && prime[j]*i < M; j++)
    		{
    			notprime[prime[j]*i] = 1;
    			if(i%prime[j] == 0) break;
    		}	
    	}
    }
    
    int vis[M];
    struct node{
    	int x,step;
    };
    queue<node>q;
    
    int bfs(int n, int m)
    {
    	node first_node;
    	first_node.step = 0;
    	first_node.x = n;
    	q.push(first_node);
    	vis[n] = 1; //标记n走过 
    	node next; 
    	while(!q.empty())
    	{
    		node tmp = q.front();
    		int x = tmp.x;
    		q.pop();
    		if(x == m) return tmp.step; //如果到了终点 
    		int num_1 = x/1000, num_2 = (x%1000)/100, num_3 = (x-num_1*1000-num_2*100)/10, num_4 = x%10;
    		//千位 
    		for(int i = 1; i < 10; i++)
    		{
    			int num = i*1000 + num_2*100 + num_3*10 + num_4;
    			if(!vis[num] && !notprime[num])
    			{
    				next.x = num;
    				next.step = tmp.step + 1;
    				q.push(next);
    				vis[num] = 1;	
    			}
    		}
    		//百位和十位 
    		for(int i = 0; i < 10; i++)
    		{
    			int num = num_1*1000 + i*100 + num_3*10 + num_4;
    			if(!vis[num] && !notprime[num])
    			{
    				next.x = num;
    				next.step = tmp.step + 1;
    				q.push(next);
    				vis[num] = 1;	
    			}
    			
    			 num = num_1*1000 + num_2*100 + i*10 + num_4;
    			 if(!vis[num] && !notprime[num])
    			{
    				next.x = num;
    				next.step = tmp.step + 1;
    				q.push(next);
    				vis[num] = 1;	
    			}
    		}
    		//个位 
    		for(int i = 1; i < 10; i = i+2)
    		{
    			int num = num_1*1000 + num_2*100 + num_3*10 + i;
    			if(!vis[num] && !notprime[num])
    			{
    				next.x = num;
    				next.step = tmp.step + 1;
    				q.push(next);
    				vis[num] = 1;	
    			}
    		}
    	}
    	return -1;
    }
    
    
    
    
    
    int main()
    {
    	init();
    	int t;
    	cin>>t;
    	while(t--){
    		while(!q.empty()) q.pop();
    		for(int i = 0; i < M; i++) vis[i] = 0;
    		int n,m;
    		cin>>n>>m;
    		int ans = bfs(n,m);
    		if(ans == -1) 
    			cout<<"Impossible"<<endl; 
    		else 
    			cout<<ans<<endl;
    	}
    	
    	
    	return 0;
    }
    

     代码很长,思路不难。把四位数拿出来,循环看是不是素数。加上bfs就ok了。

  • 相关阅读:
    swift中的"类型擦除"
    Swift Pointer 使用指南
    Swift Method Dispatching — a summary of my talk at Swift Warsaw
    Swift库二进制接口(ABI)兼容性研究
    编译器最重要的工作就是确定对象内存模型
    Objective-C类成员变量深度剖析--oc对象内存模型
    Swift进阶之内存模型和方法调度
    Swift 对象内存模型探究(一)
    编程领域中的 "transparent" 和 "opaque"
    structure vs class in swift language
  • 原文地址:https://www.cnblogs.com/stul/p/10341432.html
Copyright © 2020-2023  润新知