您的位置:首页 > 其它

POJ 1426 Find The Multiple (BFS + 同余定理)

2017-03-14 20:33 357 查看
题意:给出一个整数n,(1 <= n <= 200)。求出任意一个它的倍数m,要求m必须只由十进制的'0'或'1'组成。

解题思路:深深体会到,学搜索前要先去学一下动态规划,懂得状态是怎么一回事情, 这题也是

首先拿到题目我们想到的肯定就是一个一个去枚举, 每一位是枚举1 还是 0, 那么问题来了,答案总共可能会有100位,那么怎么办呢

大体思路不变, 我们首先要解决达到什么状态停止搜索,很明显那就是余数等于0, 那么我们可以从高位到底位一个一个枚举,同时配合同余

定理,那么问题又来了,如果是dfs,我们怎么判断它的深度呢,好像无从下手,,,那我想想要尽量早的结束,我就想用bfs了, 那么bfs搜索过程可以剪枝吗

答案是可以的,因为n的范围在200 以内,那么我们可以给每种状态用余数标记,出现相同的就大可不必继续搞下去了。那么vis开200就足够了,接下来是输出的问题

很明显具体数字我们并不关心,我们只关心她的每一位是什么就可以啦!!!!

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


#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#include<string>
using namespace std;
struct P
{
string s;
int r;
P(string s,int r):s(s),r(r){}
P(){}
};
int vis[222];
queue<P>que;
void bfs(int n)
{
int i,j;
memset(vis,0,sizeof(vis));
while(!que.empty()) que.pop();
P p = P("1",1%n);
vis[1%n]=1;
que.push(p);
while(!que.empty()) {
p = que.front();
que.pop();
if(p.r==0) {
cout<<p.s<<endl;
return;
}
for(i=0;i<2;i++) {
P tmp = p;
char ch ='0'+i;
tmp.s+=ch;
tmp.r=(tmp.r*10+i)%n;
if(vis[tmp.r]) continue;
vis[tmp.r]=1;
que.push(tmp);
}
}
return ;
}
int main()
{
int n,i,j;
ios::sync_with_stdio(false);
while(cin>>n && n) {
bfs(n);
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: