1. 程式人生 > >2018-2019 ICPC, NEERC, Southern Subregional Contest:A. Find a Number(BFS)

2018-2019 ICPC, NEERC, Southern Subregional Contest:A. Find a Number(BFS)

A. Find a Number time limit per test 3 seconds memory limit per test 256 megabytes inputstandard input outputstandard output You are given two positive integers d and s. Find minimal positive integer n which is divisible by d and has sum of digits equal to s.

Input The first line contains two positive integers d and s (

1d500,1s5000)(1\le d≤500,1≤s≤5000) separated by space.

Output Print the required number or -1 if it doesn’t exist.

Examples input 13 50 output 699998 input 61 2 output 1000000000000000000000000000001 input 15 50 output -1

思路:因為總共的狀態數為dsd*s,所以可以從x%d=0digts(x)=0x\%d=0,digts(x)=0開始BFS,直到找到答案或遍歷完所有狀態。

#include<bits/stdc++.h>
using namespace std;
int v[510][5010];
struct lenka
{
    int len,mod,sum;
    char s[600];
    lenka()
    {
        len=-1;
        mod=sum=0;
        memset(s,0,sizeof s);
    }
};
int main()
{
    int d,s;
    cin>>d>>s;
    queue<lenka>p;
    lenka now;
    p.push(now);
    while(!p.empty())
    {
        now=p.front();p.pop();
        for(int i=0;i<=9;i++)
        {
            lenka nex=now;
            nex.len++;
            nex.s[nex.len]=i+'0';
            nex.mod=(nex.mod*10+i)%d;
            nex.sum+=i;
            if(v[nex.mod][nex.sum]||nex.sum>s)continue;
            v[nex.mod][nex.sum]=1;
            if(nex.mod==0&&nex.sum==s)
            {
                puts(nex.s);return 0;
            }
            p.push(nex);
        }
    }
    puts("-1");
    return 0;
}