AtCoder Beginner Contest 161D 题解

原题链接:洛谷链接AtCoder链接

思路

每次根据上一位,计算下一位为TA-1/TA/TA+1,放入queue中,最后输出第$K$次弹出的整数。

注意事项

  • 不用long longWA
  • 上一位为$0$时下一位不能为$-1$!(要特判)
  • 上一位为$9$时下一位不能为$10$!(也要特判)

代码

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <cstdio>
#include <queue>
using namespace std;

typedef long long LL;

int main(int argc, char** argv)
{
    int k;
    scanf("%d", &k);
    queue<LL> q;
    for(int i=1; i<10; i++) q.push(i);
    while(true)
    {
        LL x = q.front(); q.pop();
        if(--k == 0)
        {
            printf("%lld\n", x);
            return 0;
        }
        int r = x % 10LL;
        x *= 10LL;
        x += r;
        if(r > 0) q.push(x - 1);
        q.push(x);
        if(r < 9) q.push(x + 1);
    }
    return 0;
}
使用 Hugo 构建
主题 StackJimmy 设计