您的位置:首页 > 其它

POJ 1426 Find The Multiple (bfs搜索)

2016-03-12 21:01 555 查看
                  题意:求一个n的倍数且这个数每位只能是0和1。

                 题目链接:点击打开链接

                   思路:既然只能包含0和1,那么可以按位搜索,后来又想想这个数是n的倍数,可以记录余数是否访问减少搜索量,因此可以直接枚举每一位时搜索余数。通过记录路径来输出值。

                 #include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
using namespace std;
typedef long long LL;
const int maxn = 200;
#define INF 0x3f3f3f3f
int n;
int vis[maxn];//记录余数访问过没且当前位是多少
int pre[maxn];//记录路径
int main()
{
while(scanf("%d",&n)!=EOF&&n)
{
pre[1]=-1;
memset(vis,-1,sizeof vis );
vis[1]=1;
queue<int>q;
q.push(1);
while(!q.empty())
{
int a=q.front();
q.pop();
if(a==0) break;
int b=a*10;//当前位为0
if(vis[b%n]==-1)
{
vis[b%n]=0;
q.push(b%n);
pre[b%n]=a;
}
b++;//当前位为1
if(vis[b%n]==-1)
{
vis[b%n]=1;
q.push(b%n);
pre[b%n]=a;
}
}
stack<int> s;
s.push(vis[0]);
int b=pre[0];
while(b!=-1)
{
s.push(vis[b]);
b=pre[b];
}
while(!s.empty())
{
printf("%d",s.top());
s.pop();
}
puts("");
}
return 0;
}
                
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: