基准时间限制:1 秒 空间限制:131072 KB 分值: 40
难度:4级算法题
给定一个自然数N,找出一个M,使得M > 0且M是N的倍数,并且M的10进制表示只包含0或1。求最小的M。
例如:N = 4,M = 100。
Input
输入1个数N。(1 <= N <= 10^6)
Output
输出符合条件的最小的M。
Input示例
4
Output示例
100
思路:
直接搜索肯定超时,可以标记状态。状态为当前的数对n的模。可以用同余定理证明。还需要保存当前数,long long肯定存不下。可以考虑用int数组或string,但 int数组超时,改为string以后发现快太多了,不明觉厉。
代码:
#include<stdio.h>
#include<string.h>
#include<queue>
#include<algorithm>
#include<math.h>
#include<stdlib.h>
#include<set>
#include<iostream>
using namespace std;
#define MAXN 1000005
int n;
bool vis[MAXN];
struct node
{
string num;
int mod,step;
}p;
void bfs()
{
queue<node> q;
memset(vis,0,sizeof vis);
p.num="1";
p.step=1;
p.mod=1%n;
q.push(p);
vis[p.mod]=1;
while(!q.empty())
{
node top=q.front(); q.pop();
if(top.mod==0)
{
cout<< top.num << endl;
return;
}
if(!vis[(top.mod*10)%n])
{
p.num=top.num+"0";
p.mod=(top.mod*10)%n;
vis[(top.mod*10)%n]=1;
p.step=top.step+1;
if(p.mod==0)
{
cout<< p.num << endl;
return;
}
q.push(p);
}
if(!vis[(top.mod*10+1)%n])
{
p.num=top.num+"1";
p.mod=(top.mod*10+1)%n;
vis[(top.mod*10+1)%n]=1;
p.step=top.step+1;
if(p.mod==0)
{
cout<< p.num << endl;
return;
}
q.push(p);
}
}
}
int main()
{
while(~scanf("%d",&n))
{
bfs();
}
return 0;
}