Prime Path POJ - 3126 bfs
阿新 • • 發佈:2018-12-23
剛開始在執行函式中間不小心打錯成了que[rear].s
修正了以後發現各種輸出0emmm
要用rear-1啊
簡單的廣搜求最短,列舉素數
#include<stdio.h>
#include<string.h>
int pd[10005];
int book[10005];
int cishu,head,rear;
struct node{
int s,pre;
}que[100000];
bool bianhuan(int x,int y)
{
int q[5],p[5],ans=0;
for(int i=1;i<=4;i++)
{
q[i] =x%10;
x=x/10;
p[i]=y%10;
y=y/10;
if(p[i]==q[i]) ans++;
}
if(ans==3) return true;
else return false;
}
void bfs(int a,int b)
{
int flag=0;
if(b==a) return ;
while(head<rear)
{
for(int i=1009;i<=9973;i++)
{
if(pd[i]==0 && book[i]==0)
{
if(bianhuan(que[head].s,i)==true)
{
book[i]=1;
que[rear].s=i;
que[rear].pre=head;
rear++;
//printf ("%d\n",i);
if(i==b)
{
//printf("%d",que[rear-1].pre);
flag=1;
break;
}
}
}
/*if(i==b)
{
printf("i b %d %d\n",i,b);
flag=1;
break ;
}*/
}
//printf("head rear %d %d\n",head,rear);
//printf("%d\n",flag);
if(flag==1)
break;
head++;
}
}
void ss(int n)
{
pd[1]=1;//用0代表素數
for(int i=3;i<=n;i++)
if(i%2==0) pd[i]=1;
for(int i=3;i<=n/2;i++)
if(pd[i]==0)
{
for(int j=i+1;j<=n;j++)
if(j%i==0) pd[j]=1;
}
}
/*int zhixing(int n)
{
int cout=0;
while(que[rear].pre!=0)
{
rear=que[rear].pre;
cout++;
}
return cout+1;
}*/
void zhixing(int n)
{
if(que[n].pre!=-1)
{
cishu++;
zhixing(que[n].pre);
}
}
void shuchu(int x)
{
if(que[x].pre!=-1)
{
printf("%d\n",que[x].s);
shuchu(que[x].pre);
}
}
int main()
{
int n,a,b;
memset(pd,0,sizeof(pd));
ss(10000);
scanf("%d",&n);
while(n--)
{
cishu=0;
head=1;
rear=1;
memset(book,0,sizeof(book));
memset(que,0,sizeof(que));
scanf("%d%d",&a,&b);
que[rear].s=a;
que[rear].pre=-1;
rear++;
book[a]=1;
bfs(a,b);
zhixing(rear-1);//重點!!!!
//shuchu(rear-1);
printf("%d\n",cishu);
}
return 0;
}