POJ 1426 Find The Multiple

本文介绍了一种算法,用于找到给定整数n的最小倍数m,且m仅由0和1组成。通过使用广度优先搜索,并利用余数优化避免重复计算,文章详细解释了实现这一目标的具体步骤。

大意:给定一个整数n,找到最小的n的倍数m,m只能有0/1组成。

思路:给定如图的二叉树,沿着路径一直搜索即可,初始条件为1,然后不断的在后面加0或者1,直到找到n的倍数为止。其中,余数相同的可以不再扩展。

           1  
   /     \
   /       \
  /         \
    10        11
  /    \      /    \
 /      \    /       \
100 101 110 111

View Code
#include <iostream>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cstring>
#include <cmath>
#include <vector>
#include <queue>
#include <stack>
#include <algorithm>
using namespace std;

typedef long long LL;

LL n;

struct node
{
    string ans;
    node() {ans = ""; }
};

int read_case()
{
    scanf("%lld", &n);
    if(!n) return 0;
    return 1;
}

LL Mod(string s, int n)
{
    int len = s.length();
    int ans = 0;
    for(int i = 0; i < len; i++)
    {
        ans = (ans*10+s[i]-'0')%n;
    }
    return ans;
}

bool vis[220];

node bfs()
{
    queue<node> Q;
    node cur, next;
    cur.ans = "1";
    memset(vis, 0, sizeof(vis));
    Q.push(cur);
    LL m;
    for(;;)
    {
        cur = Q.front(); Q.pop();
        if(Mod(cur.ans, n) == 0) return cur;
        next = cur;
        next.ans = cur.ans + "1";
        m = Mod(next.ans, n);
        if(!vis[m])
        {
            Q.push(next);
            vis[m] = 1;
        }
        next = cur;
        next.ans = cur.ans + "0";
        m = Mod(next.ans, n);
        if(!vis[m])
        {
            Q.push(next);
            vis[m] = 1;
        }
    }
}

void solve()
{
    node ans = bfs();
    cout<<ans.ans<<endl;
}

int main()
{
    while(read_case())
    {
        solve();
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/Buck-Meister/archive/2013/04/24/3041177.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值