HDU---4474 Yet Another Multiple Problem【广度优先搜索】

Problem Description
There are tons of problems about integer multiples. Despite the fact that the topic is not original, the content is highly challenging. That’s why we call it “Yet Another Multiple Problem”.
In this problem, you’re asked to solve the following question: Given a positive integer n and m decimal digits, what is the minimal positive multiple of n whose decimal notation does not contain any of the given digits?
 

Input
There are several test cases.
For each test case, there are two lines. The first line contains two integers n and m (1 ≤ n ≤ 10 4). The second line contains m decimal digits separated by spaces.
Input is terminated by EOF.
 

Output
For each test case, output one line “Case X: Y” where X is the test case number (starting from 1) while Y is the minimal multiple satisfying the above-mentioned conditions or “-1” (without quotation marks) in case there does not exist such a multiple.
 

Sample Input
  
  
2345 3 7 8 9 100 1 0
 

Sample Output
  
  
Case 1: 2345 Case 2: -1
题意:
给一个数n(1<n<10000),求n的最小的倍数x,使得x不包含m个特定的数字。
输入的第一个数表示n,第二个数表示m。接下来的一行有m个数字,表示不包含的数字。
输出为答案x,若没有解,则输出-1.
代码:
#include <iostream>
#include <cstring>
#include <queue>
#define N 10005
using namespace std;

bool vis[N],del[10];
int n;
int pre[N],text[N];

bool bfs();
void print();

int main(void)
{
    int k;
    int m=0,cas=1;
    while(cin>>n>>m)
    {
        memset(vis,0,sizeof(vis));
        memset(del,0,sizeof(del));
        while(m--)
        {
            cin>>k;
            del[k]=1;
        }
        cout<<"Case "<<cas++<<": ";
        if(!bfs())
            cout<<-1<<endl;
        else
            print();
    }
    return 0;
}

bool bfs()
{
    queue<int> Q;
    Q.push(0);
    int cur;
    while(Q.size())
    {
        cur=Q.front();
        Q.pop();
        for(int i=0; i<10; i++)
        {
            if(del[i]==true||cur==0&&i==0)  //如果是不允许使用的数字或者是当余数和数字都为0,继续
                continue;
            int yu=(cur*10+i)%n;  //计算新的余数
            if(vis[yu])    //已经到达过,不保存
                continue;
            text[yu]=i;   //记录到达新余数时的数字i
            vis[yu]=true;
            pre[yu]=cur;   //记录到达这个余数的前面那个余数
            Q.push(yu);
            if(yu==0)   //若此时余数为0,说明获得答案,退出
                return true;
        }
    }
    return false;
}

void print()
{
    int p=0,k=0;
    int ans[N];
    while(p||!k)
    {
        ans[k++]=text[p];
        p=pre[p];
    }
    for(int i=k-1; i>=0; i--)
        cout<<ans[i];
    cout<<endl;
}


  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值