zoj 1530

给定 一个n求能够被n整除且只含0和1的数。

BFS写法,每次添加0和1,看能否被n整除

代码实现

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
using namespace std;


queue <long long >q;
int main()
{
    int n;
    while(scanf("%d",&n)!=EOF&&n)
    {
        while(!q.empty())
            q.pop();
        long long temp=1;
        q.push(temp);
        while(!q.empty())
        {
            temp=q.front();
            if(temp%n==0)
                break;
            q.pop();
            q.push(temp*10+1);
            q.push(temp*10);
        }
        printf("%lld\n",temp);
    }
    return 0;
}

可以根据数论中的同余概念进行优化,在求得的数超过long long的情况下也可以得到最后的答案,就是每次对得到的数%n ,用余数去扩展另一个数

的同时,用一个string 来存储得到的数。用这种方式写的时候MLE了好几次,最后得出错误的原因是没用top变量进行改变,直接用的num自身进行变化。

代码

#include <stdio.h>
#include <string.h>
#include <algorithm>
#include <queue>
#include <string>
#include <iostream>
using namespace std;


typedef struct node
{
    string s;
    int temp;
}Num;


queue <Num>q;


Num num,top;
string str;
int res;


int main()
{
    int n;
    while(scanf("%d",&n)!=EOF&&n)
    {
        while(!q.empty())
            q.pop();
        str="1";
        res=1;
        num.s=str;
        num.temp=res;
        q.push(num);
        while(!q.empty())
        {
            top=q.front();
            if(top.temp%n==0)
                break;
            q.pop();
            num.s=top.s+"1";
            num.temp=(top.temp*10+1)%n;
            q.push(num);
            num.s=top.s+"0";
            num.temp=(top.temp*10)%n;
            q.push(num);
        }
        cout <<top.s<<endl;
    }
    return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值