Find The Multiple
Description
Given a positive integer n, write a program to find out a nonzero multiple m of n whose decimal representation contains only the digits 0 and 1. You may assume that n is not greater than 200 and there is a corresponding m containing no more than 100 decimal digits.
Input
The input file may contain multiple test cases. Each line contains a value of n (1 <= n <= 200). A line containing a zero terminates the input.
Output
For each value of n in the input print a line containing the corresponding value of m. The decimal representation of m must not contain more than 100 digits. If there are multiple solutions for a given value of n, any one of them is acceptable.
Sample Input
2 6 19 0
Sample Output
10 100100100100100100 111111111111111111
题意:
求只由0和1组成并且是n的倍数的数,只要求输出一个
思路:
很明显它数再大应该也不会爆long long,那么直接暴力DFS吧
代码:
#include<stdio.h>
#define ll long long int
int n,flag;
void dfs(ll x,int i)
{
if(i>=19||flag)
return ;
if(x%n==0)
{
printf("%lld\n",x);
flag=1;
return ;
}
dfs(x*10,i+1);
dfs(x*10+1,i+1);
}
int main()
{
while(~scanf("%d",&n)&&n)
{
flag=0;
dfs(1,0);
}
return 0;
}
竟然A了。。。原本想着不会这么简单。。
上网搜了一下代码,原来这是道BFS题。。。。
看了一下大神的BFS,真心看不懂
啊,涉及到最短路径,二叉树,(还没学
)


来一波:
思路:化为bfs求最短路径问题,关键有几点:
#include<iostream>
#include<string.h>
using namespace std;
const int Max = 201;
struct node
{
int num;
int rem;
node *pre;
}; // 队列中每个结点的结构。
void print(node n)
{
if(n.pre == NULL)
cout << n.num;
else
{
print(*n.pre);
cout << n.num;
}
} // 递归构造出答案。
int main()
{
node queue[Max];
bool remain[Max];
int n;
while(cin >> n && n != 0)
{
memset(remain, false, sizeof(remain));
remain[1] = true;
queue[1].num = 1;
queue[1].rem = 1;
queue[1].pre = NULL;
int head = 1, tail = 2; // 队列第一个结点,队列初始化。
bool flag = false; // 找到答案的标志。
node ans; // 目标结点。
while(!flag)
{
int count = tail - head;
while(count --)
{
node now;
for(int i = 0; i <= 1; i ++)
{
now.num = i;
now.rem = (queue[head].rem * 10 + i) % n;
now.pre = &queue[head];
if(now.rem == 0)
{
ans = now;
flag = true;
}
else if(!remain[now.rem])
{
remain[now.rem] = true;
queue[tail++] = now; // 注意要入列,一开始忘了wa了很久。
}
}
head ++;
}
}
print(ans);
cout << endl;
}
return 0;
}
ps:待我学了之后重刷它BFS