[ABC443F] Non-Increasing Number

· · 题解

题解

题目传送门

思路

设 f_{x,c} 表示与 x 模 n 同余的整数的最小位数,且最后一位为 c。
很明显 f_{(10\times x+cc) \mod n,cc}=f_{x,c}+1,计算时需要用 bfs,且要算出每个 f_{x,c} 是由哪个数得到的。
计算答案时,从第一个满足 x=0 的 f_{x,c} 开始,把 c 加入答案序列中,找 f_{x,c} 是由哪个数得到的,然后把 x 和 c 变成这个数对应的下标,最后将得到的答案序列翻转并输出。
当然,要注意答案可能为 -1。

AC Code

#include <bits/stdc++.h>
#define int long long
using namespace std;
inline int read()
{
    int x = 0,p = 1;
    char c = getchar();
    while(c > '9' || c < '0')   p = c == '-' ? -1 : 1,c = getchar();
    while(c >= '0' && c <= '9') x = (x << 1) + (x << 3) + (c ^ 48),c = getchar();
    return p * x;
}
template<typename _Tp> inline void _write(_Tp x) { if(x > 9) _write(x / 10); putchar(x % 10 | 48); }
template<typename _Tp> inline void write(_Tp x) { if(x < 0) putchar('-'),x = -x; _write(x); }
template<typename _Tp> inline void writeln(_Tp x) { write(x); puts(""); }
const int N = 3e7 + 10;
const int inf = 1e9;
int n,f[N],to[N];
signed main()
{
    n = read();
    for(int i = 0;i <= n * 10;i++)
        f[i] = inf,to[i] = -1;
    f[0] = 0;
    queue<int> q; q.push(0);
    int idx,c,x;
    while(!q.empty())
    {
        idx = q.front(); q.pop();
        c = idx % 10,x = idx / 10;
        for(int i = max(1ll,c),xx,idx2;i <= 9;i++)
        {
            xx = (10 * x + i) % n;
            idx2 = 10 * xx + i;
            if(f[idx2] != inf)  break;
            f[idx2] = f[idx] + 1;
            q.push(idx2);
            to[idx2] = idx;
            if(xx == 0)
            {
                string ans = "";
                int cur = idx2;
                while(cur)  ans.push_back((cur % 10) | 48),cur = to[cur];
                reverse(ans.begin(),ans.end());
                cout << ans << endl;
                return 0;
            }
        }
    }
    puts("-1");
    return 0;
}

Atcoder提交记录