51nod1109 01组成的倍数 数据结构

13 篇文章 0 订阅

题目:


给定一个自然数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


思路:因为n比较大,倍数肯定会超long long ,所以设计一个数组,记录每一位的数据,和每一位的前面的位置下标即可,找到答案,DFS输出即可。


#include <iostream>
#include <cstdio>
#include <string>
#include <cstring>
#include <fstream>
#include <algorithm>
#include <cmath>
#include <queue>
#include <stack>
#include <vector>
#include <map>
#include <set>
#include <iomanip>

using namespace std;
#define maxn 2000005
#define MOD 1000000007
#define mem(a , b) memset(a , b , sizeof(a))
#define LL long long
#define INF 1000000000

struct node
{
    int x ,per;
}ans[maxn];

bool vis[maxn];
int n , num;

void DFS(int pos)
{
    int res = ans[pos].per;
    if(res <= 0)
    {
        printf("1");
        return;
    }
    DFS(res);
    printf("%d" , ans[res].x);
}

void BFS()
{
    num = 1;
    mem(vis , 0);
    node cur , tmp;
    cur.x = 1 , cur.per = 0;
    queue<node>q;
    ans[0].x = 1;
    ans[0].per = 0;
    while(!q.empty()) q.pop();
    q.push(cur);
    while(!q.empty())
    {
        tmp = q.front();
        q.pop();
        for(int i = 0 ; i <= 1 ; i ++)
        {
            cur.x = tmp.x * 10 + i;
            cur.x %= n;
            if(!vis[cur.x])
            {
                cur.per = num;
                vis[cur.x] = 1;
                ans[num].x = i;
                ans[num].per = tmp.per;
                q.push(cur);
                if(cur.x == 0)
                {
                    DFS(num);
                    printf("%d\n" , i);
                    return;
                }
                num++;
            }
        }
    }
}

int main()
{
    while(scanf("%d" , &n) != EOF)
    {
        if(n == 1)
        {
            printf("1\n");
            continue;
        }
        BFS();
    }
    return 0;
}


评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值