一道关于隐式图的搜索题,bfs和dfs都行,,
题意:给你一个数,让你求一个数是该数的倍数,但是要求该数只有0和1构成。需要注意的是要用bfs时需要自己写一下队列。
BFS:
#include<iostream>
#include<string.h>
#include<string>
#include<cstdio>
using namespace std;
typedef long long L;
L Queue[20000000];
int rear,front;
int n;
void init()
{
rear=0;
front=1;
Queue[0]=1;
}
void Qpush(L e)
{
Queue[front]=e;
++front;
}
void Qpop(L &e)
{
e=Queue[rear];
++rear;
}
bool Empty()
{
return rear==front;
}
L bfs()
{
while(!Empty())
{
L e;
Qpop(e);
if(e%n==0) return e;
e=e*10;
Qpush(e);
e=e+1;
Qpush(e);
}
}
int main()
{
while(~scanf("%d",&n),n)
{
init();
printf("%lld\n",bfs());
}return 0;
}
DFS:
#include<cstdio>
#include<string.h>
#include<iostream>
using namespace std;
int n;
typedef long long L;
bool flag;
void dfs(L now,int cur)
{
if(flag||cur==19) return;//当cur大于19时超出了L的范围需要回溯
if(now%n==0)
{
printf("%lld\n",now);
flag=true;
return;
}
dfs(now*10,cur+1);
dfs(now*10+1,cur+1);
}
int main()
{
while(~scanf("%d",&n),n)
{
flag=false;
dfs(1,0);
}
}