You are given two positive integers dd and ss. Find minimal positive integer nn which is divisible by dd and has sum of digits equal to ss.
Input
The first line contains two positive integers dd and ss (1≤d≤500,1≤s≤50001≤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
一开始想的时候根本不会。。。
看了题解之后发现才会的。。
思路:
建立一个表示余数和总和的二维数组,然后利用bfs逐步推进。
每位进行'0'-'9'判定。
代码如下:
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <iostream>
#include <queue>
using namespace std;
int vis[505][5005];
int d,s;
struct node
{
int mod;
int sum;
string s;
};
string bfs ()
{
queue<node>q;
node now,next;
now.mod=0; now.sum=0; now.s="";
q.push(now);
vis[0][0]=1;
while (!q.empty())
{
now=q.front();
q.pop();
if(now.sum>s)
continue;
if(now.mod==0&&now.sum==s)
{
return now.s;
}
for (int i=0;i<=9;i++)
{
next.mod=(now.mod*10+i)%d;
next.sum=now.sum+i;
if(!vis[next.mod][next.sum])
{
next.s=now.s+(char)('0'+i);
q.push(next);
vis[next.mod][next.sum]=1;
}
}
}
return "-1";
}
int main()
{
memset (vis,0,sizeof(vis));
scanf("%d%d",&d,&s);
cout<<bfs()<<endl;
return 0;
}