CF1070A Find a Number

Description

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

Solution

\(f[i][j]\) 表示生成一个和为 \(i\)\(\bmod 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;
}

相关文章:

  • 2022-12-23
  • 2021-08-06
  • 2021-09-16
  • 2022-12-23
  • 2022-12-23
猜你喜欢
  • 2021-11-25
  • 2021-12-15
  • 2021-12-30
  • 2021-10-30
  • 2022-12-23
  • 2022-02-05
  • 2021-06-16
相关资源
相似解决方案