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

本文介绍了一种算法,用于寻找一个整数n的倍数m,该倍数仅由0和1组成,且不超过100位。通过使用BFS算法结合同余定理,有效地解决了这一问题。


题意:给出一个整数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;
}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值