给定 一个n求能够被n整除且只含0和1的数。
BFS写法,每次添加0和1,看能否被n整除
代码实现
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;
queue <long long >q;
int main()
{
int n;
while(scanf("%d",&n)!=EOF&&n)
{
while(!q.empty())
q.pop();
long long temp=1;
q.push(temp);
while(!q.empty())
{
temp=q.front();
if(temp%n==0)
break;
q.pop();
q.push(temp*10+1);
q.push(temp*10);
}
printf("%lld\n",temp);
}
return 0;
}
可以根据数论中的同余概念进行优化,在求得的数超过long long的情况下也可以得到最后的答案,就是每次对得到的数%n ,用余数去扩展另一个数
的同时,用一个string 来存储得到的数。用这种方式写的时候MLE了好几次,最后得出错误的原因是没用top变量进行改变,直接用的num自身进行变化。
代码
#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <string>
#include <iostream>
using namespace std;
typedef struct node
{
string s;
int temp;
}Num;
queue <Num>q;
Num num,top;
string str;
int res;
int main()
{
int n;
while(scanf("%d",&n)!=EOF&&n)
{
while(!q.empty())
q.pop();
str="1";
res=1;
num.s=str;
num.temp=res;
q.push(num);
while(!q.empty())
{
top=q.front();
if(top.temp%n==0)
break;
q.pop();
num.s=top.s+"1";
num.temp=(top.temp*10+1)%n;
q.push(num);
num.s=top.s+"0";
num.temp=(top.temp*10)%n;
q.push(num);
}
cout <<top.s<<endl;
}
return 0;
}