Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

baneHunter

Posted by 1340502116 at 2016-07-18 15:05:09 on Problem 3126
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
const int MAXN=10005;
struct Node{
	int x,step;
	Node(){}
	Node(int x,int step)
	{
		this->x=x;
		this->step=step;
	}
};
int src,ter;
int vis[MAXN];
bool isPrime(int x)
{
	if(x<1000)	return false;
	for(int i=2;i*i<=x;i++)
	{
		if(x%i==0)	return false;
	}
	return true;
}
void bfs()
{
	memset(vis,0,sizeof(vis));
	queue<Node> que;
	que.push(Node(src,0));
	vis[src]=1;
	while(!que.empty())
	{
		Node now=que.front();que.pop();
		if(now.x==ter)
		{
			cout<<now.step<<endl;
			return ;
		}	
		int buf[2][4];
		buf[0][0]=(now.x/1000)*1000;
		buf[0][1]=((now.x/100)%10)*100;
		buf[0][2]=((now.x%100)/10)*10;
		buf[0][3]=now.x%10;
		buf[1][0]=1000;
		buf[1][1]=100;
		buf[1][2]=10;
		buf[1][3]=1;
		for(int i=0;i<4;i++)
		{
			int tmp=0;
			for(int j=0;j<4;j++)
			{
				if(i==j)	continue;
				tmp+=buf[0][j];
			}
			for(int j=0;j<=9;j++)
			{
				int net=tmp+buf[1][i]*j;
				if(!vis[net]&&isPrime(net))
				{
					vis[net]=1;
					que.push(Node(net,now.step+1));
				}		
			}
		}
	}
	cout<<"Impossible"<<endl;
}
int main()
{
	int T;
	cin>>T;
	while(T--)
	{
		cin>>src>>ter;
		bfs();
	}
	return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator