1109 01组成的N的倍数

给定一个自然数N,找出一个M,使得M > 0且M是N的倍数,并且M的10进制表示只包含0或1。求最小的M。
例如:N = 4,M = 100。
Input
输入1个数N。(1 <= N <= 10^6)
Output
输出符合条件的最小的M。
Input示例
4
Output示例
100
题解:因为要找到最小的,所以一开始就想到用bfs。考虑了一下,发现有可能会爆longlong,不过还是尝试了一下,果然错了。想到用大数,觉得有点麻烦,后来才知道维护一个余数,利用同余定理,同时可以进行剪枝,使得复杂度在O(1e6)内,十分巧妙。

代码:

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <cstring>
#include <string>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <vector>
#include <set>
#include <stack>
#include <map>
#include <cmath>
#include <ctime>
using namespace std;
typedef long long ll;
typedef pair<ll, int> P;
const int INF = 0x3f3f3f3f;
const ll LINF = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-10;
const int maxn = 1e6+7;
const int mod = 1e9+7;

int n;
struct G{
    string s;
    int num;
    G(string s,int num):s(s),num(num){}
    G(){}
};
int vis[maxn];
queue<G> que;

int main()
{
    scanf("%d",&n);
    G now;
    now = G("1",1%n);
    memset(vis,0,sizeof(vis));
    vis[1%n] = 1;
    que.push(now);
    while(!que.empty())
    {
        now = que.front();
        que.pop();
        if(now.num==0){
            cout<<now.s<<endl;
            break;
        }
        int a;
        a = now.num*10;
        if(!vis[a%n]) que.push(G(now.s+"0",a%n)),vis[a%n] = 1;
        if(!vis[a%n+1]) que.push(G(now.s+"1",(a+1)%n)),vis[a%n+1] = 1;
    }
    return 0;
}

涉及的知识:

1、bfs。

2、同余定理。

经验:

1、从小到大的枚举之类的有一个大致方向的查找应该想到bfs。

2、约数倍数,应该想到mod,同时如果爆了ll,可以不急着想大数,往同余方向想想也是可以的。

3、string有时挺有用的,比较方便。


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值