[CF1070A] Find a Number

CF1070A Find a Number

Description

给定两个数 (d le 500)(s le 5000),求最小的 (n) 使得 (d|n) 并且 (n) 的各位数字之和为 (s)

Solution

(f[i][j]) 表示生成一个和为 (i)(mod d=j) 的数字的最小 (n) 的末位数字

用 BFS 实现即可

#include <bits/stdc++.h>
using namespace std;
#define int long long
const int N = 505;
const int S = 5005;
int d,s,vis[N][S];
queue<pair<int,int>> q;
tuple<int,int,int> f[N][S];

void bfs()
{
    vis[0][0]=1;
    q.push({0,0});
    while(q.size())
    {
        int x=q.front().first,y=q.front().second;
        q.pop();
        for(int i=0;i<10;i++)
        {
            int nx=(10*x+i)%d, ny=y+i;
            if(ny<=s && vis[nx][ny]==0)
            {
                vis[nx][ny]=1;
                f[nx][ny]=make_tuple(x,y,i);
                q.push({nx,ny});
            }
        }
    }
}

void print(int x,int y)
{
    if(x||y)
    {
        print(get<0>(f[x][y]),get<1>(f[x][y]));
        cout<<(char)('0'+get<2>(f[x][y]));
    }
}

signed main()
{
    ios::sync_with_stdio(false);
    cin>>d>>s;
    bfs();
    if(vis[0][s])
    {
        print(0,s);
    }
    else cout<<-1;
}

原文地址:https://www.cnblogs.com/mollnn/p/13323950.html