题解 P1602 【Sramoc问题】

题目链接

Solution Sramoc问题

题目大意:给定\(k\)\(m\),试求一个最小的\(x\)满足其每一位在\(0\)\(k - 1\)之前,且\(m\;|\;x\)

分析:显然我们可以随手打出一个\(bfs\),枚举\(0\)\(k-1\)添在当前数后面,根据\(bfs\)的性质,最先搜到的即为答案

#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
typedef long long ll;
int out[32],p;
inline void write(ll x){
    p = 0;
    if(x == 0)out[++p] = 0;
    while(x){
        out[++p] = x % 10;
        x /= 10;
    }
    for(int i = p;i >= 1;i--)putchar(out[i] + '0');
}
queue<ll> Q;
int k,m;
int main(){
    scanf("%d %d",&k,&m);
    for(int i = 1;i < k;i++)Q.push(ll(i));
    while(!Q.empty()){
        ll x = Q.front();Q.pop();
        if(x % m == 0)return write(x),putchar('\n'),0;
        for(int i = 0;i < k;i++)Q.push(x * 10 + i);
    }
    return 0;
}

但是这样做会\(TLE\;or\;MLE\),原因是因为有很多不需要搜的数我们搜过了

为什么会有不需要搜的数?

题目所求的\(ans\)满足每一位数字上的限制,下文不再赘述.在满足这个限制的前提下,求最小的\(ans\),满足\(ans \equiv 0(mod\;m)\)

那么对于两个数\(a,b\),若\(a\equiv b(mod\;m)\)则一定有\(a \times 10 + k\equiv b \times 10 + k(mod\;m)\)此时我们只需要保留\(min\{a,b\}\)

根据\(bfs\)的性质,就是最先被搜到的那个,开个\(vis\)数组记录一下\(mod\;m\)的余数有没有出现过即可

此外,此题有坑:

  • \(long long\),这个简单\(\_\_int128\)或者高精度

如果用\(\_\_int128\)记得手写输出就好,代码简单就不上注释了

#include <cstdio>
#include <algorithm>
#include <queue>
using namespace std;
typedef __int128 ll;
int out[32],p;
inline void write(ll x){
    p = 0;
    if(x == 0)out[++p] = 0;
    while(x){
        out[++p] = x % 10;
        x /= 10;
    }
    for(int i = p;i >= 1;i--)putchar(out[i] + '0');
}
queue<ll> Q;
int k,m,vis[1024];
int main(){
    scanf("%d %d",&k,&m);
    for(int i = 1;i < k;i++)Q.push(ll(i));
    while(!Q.empty()){
        ll x = Q.front();Q.pop();
        if(x % m == 0)return write(x),putchar('\n'),0;
        vis[x % m] = 1;
        for(int i = 0;i < k;i++)if(!vis[(x * 10 + i) % m])Q.push(x * 10 + i);
    }
    return 0;
}

转载于:https://www.cnblogs.com/colazcy/p/11515025.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值