CodeForces - 1070A Find a Number(记忆化宽搜)

 

A. Find a Number

time limit per test

3 seconds

memory limit per test

256 megabytes

input

standard input

output

standard output

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

Copy

13 50

output

Copy

699998

input

Copy

61 2

output

Copy

1000000000000000000000000000001

input

Copy

15 50

output

Copy

-1

 

题意:找到一个数,使得能被d整除,且每一位的和是s

 

解题思路:记忆化宽搜。用二维数组记录vis[i][j]代表当前余数为i,和为j是否访问过。因为是宽搜,所以找到的一定是最小的。

为了得到最小,要从0~9遍历。然后用一个数组记录路径即可。

 

#include <bits/stdc++.h>
using namespace std;
const int M=5005;
const int N=505;
const int INF=0x3f3f3f3f;
int d,s;
bool vis[N][M];
int pre[N][M][3];//用于输出路径

queue<int> Qx,Qy;
void bfs() {
    vis[0][0]=1;
    Qx.push(0);
    Qy.push(0);
    while(!Qx.empty()) {
        int x=Qx.front(); Qx.pop();
        int y=Qy.front(); Qy.pop();
        for(int i=0;i<=9;i++) {
            int xx=(10*x+i)%d,yy=y+i;
            if(vis[xx][yy]||yy>s)
                continue;
            vis[xx][yy]=1;
            pre[xx][yy][0]=x;
            pre[xx][yy][1]=y;
            pre[xx][yy][2]=i;
            Qx.push(xx),Qy.push(yy);
        }
    }
}

void out(int x,int y) {
    if(x==0&&y==0)
        return;
    out(pre[x][y][0],pre[x][y][1]);
    printf("%d",pre[x][y][2]);
}

int main() {
    cin>>d>>s;
    bfs();
    if(vis[0][s]==0)
        puts("-1");
    else
        out(0,s);
    return 0;
}

 

 

 

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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值