您的位置:首页 > 其它

POJ - 3126 D - Prime Path(bfs)

2017-05-23 22:18 351 查看
software gurus, do you?

— In fact, I do. You see, there is this programming contest going on... Help the prime minister to find the cheapest prime path between any two given four-digit primes! The first digit must be nonzero, of course. Here is a solution in the case above.

1033

1733

3733

3739

3779

8779

8179
The cost of this solution is 6 pounds. Note that the digit 1 which got pasted over in step 2 can not be reused in the last step – a new 1 must be purchased.

reused in the last step – a new 1 must be purchased.

Input
One line with a positive number: the number of test cases (at most 100). Then for each test case, one line with two numbers separated by a blank. Both numbers are four-digit primes (without leading zeros).

Output
One line for each case, either with a number stating the minimal cost or containing the word Impossible.

Sample Input
3
1033 8179
1373 8017
1033 1033

Sample Output
6
7
0


当时忘了bfs咋写,用dfs写崩了,所以这两天重新学了一下bfs,A掉了,轻轻松松,虽然是个水题,可是好开心啊,毕竟之前还是练得太少,还一直看题解

以后学会了算法之后就自己乖乖的做不看题解

上代码:

#include <iostream>
#include<cstring>
#include<vector>
#include<cstdio>
#include<algorithm>
#include<queue>
#include<string>
using namespace std;
const int maxn=10000;
int prim[maxn];
string shu="0123456789";
//vector<int>s;
int vis[maxn];
queue<string> ans;
int d[maxn];
string x,y;
int numstring(string s)
{
int num=0;
for(int i=0;i<s.size();i++)
{
num=num*10+s[i]-'0';
}
return num;
}
int bfs()
{
int xx=numstring(x);
d[xx]=0;
vis[xx]=1;
while(ans.size())
ans.pop();
ans.push(x);
while(ans.size())
{
string a=ans.fron
b680
t();
ans.pop();
xx=numstring(a);
if(a==y)
return d[xx];
for(int i=0;i<4;i++)
{
for(int j=0;j<10;j++)
{ if(a[i]!=shu[j])
{ char ch=a[i];
if(i==0&&j==0)
continue;
a[i]=shu[j];
int yy=numstring(a);
if(!prim[yy]&&!vis[yy])
{
ans.push(a);
vis[yy]=1;
d[yy]=d[xx]+1;
}
a[i]=ch;
}
}
}
}
return -1;

}
int main()
{
memset(prim,0,sizeof(prim));
prim[1]=1;
prim[0]=1;
for(int i=2;i<maxn;i++)
{
for(int j=i*2;j<maxn;j+=i)
prim[j]=1;
}
// for(int i=1000;i<10000;i++)
// if(!prim[i])
// s.push_back(i);
int t;
cin>>t;
while(t--)
{
cin>>x>>y;
memset(vis,0,sizeof(vis));
memset(d,0,sizeof(d));
int a= bfs();
if(a!=-1)
cout<<a<<endl;
else
cout<<"Impossible"<<endl;
}
return 0;
}


开心呀,但是想想接下来几天不怎么碰电脑又失落
电脑扔机房两天没碰电脑,今晚上回来把它带回去, 这两天估计要忙乐队排练的事情,端午节还回家不打组队赛了;

恩就这样,还有昨晚上发现的(宅老师是个宝哈哈哈哈哈哈)
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: