您的位置:首页 > 其它

poj Find The Multiple(DFS,BFS)

2016-12-26 10:50 405 查看
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,真心看不懂

啊,涉及到最短路径,二叉树,(还没学



大神博客:http://blog.sina.com.cn/s/blog_6635898a0100hwe3.html
来一波:

思路:化为bfs求最短路径问题,关键有几点:

      1.懂得用模拟除法运算的过程去做。

      2.余数为 m (1~n-1) 的情况若出现多次,则第一次出现时所构造路径肯定比后面的情况短,根据鸽巢原理,对余数重复出现的情况进行剪枝,否则会Memory Limit Exceeded,队列的长度只限制在Max = 200。

      3.构造答案的输出过程有点费心思,现在为止没想到什么好方法,只能构造出一颗二叉树,找到最后的目标节点后,再递归到根部进行输出。
代码:
#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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: