Find The Multiple POJ - 1426

本文分享了一道使用BFS算法解决的题目经验,探讨了数据规模限制下的算法选择,并通过实例讲解了同余模定理的应用。作者在解决过程中遇到了超时问题,最终发现使用unsigned long long类型可以有效避免该问题。此外,还提到了即使样例无法通过有时也能获得正确答案的情况。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这道题有点坑啊。这道题我首先想到的思路就是BFS,题目中说m不超过200位,我还以为用得用大数取模,结果TL了orz。然后看到别人的博客上用ULL并不能爆……

超时代码:
// 超时!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
#include <cstdio>
#include <iostream>
#include <queue>
#include <string>
using namespace std;

int n;

bool test(const string & s) {
    int m = 0;
    for(int i = 0; i != s.size(); i++) {
        m = ((m * 10) % n + (s[i] - '0') % n) % n;
    }
    if (m == 0)  { cout << s;  return true; }
    else return false;
}

void bfs() {
    queue<string> qu;
    qu.push("1");
    while(!qu.empty()) {
        string v = qu.front();  qu.pop();
        if (test(v))   return;
        else {
            string temp = v;
            temp.push_back('1');
            v.push_back('0');
            qu.push(temp);
            qu.push(v);
        }
    }
}

int main() {
    freopen("input.txt", "r", stdin);
    while(scanf("%d", &n) && n) {
        bfs();
        cout << endl;
    }
    return 0;
}
ac代码~
#include <cstdio>
#include <iostream>
#include <queue>
#define ULL unsigned long long
using namespace std;

int n;

void bfs() {
    queue<ULL> qu;
    qu.push(1);
    while(!qu.empty()) {
        ULL v = qu.front(); qu.pop();
        if (v % n == 0) {
            cout << v;
            return;
        }
        else {
            qu.push(v * 10);
            qu.push(v * 10 + 1);
        }
    }
}

int main() {
    freopen("input.txt", "r", stdin);
    while(scanf("%d", &n) && n) {
        bfs();
        cout << endl;
    }
    return 0;
}

总结:这道题虽然很坑,但我还是学到了不少东西
1.同余模定理
同余摸定理应用:

(a+b)%c=(a%c+b%c)%c;
(a*b)%c=(a%c*b%c)%c;

2. 有的时候样例不过也能ac。
3. 对这种数据坑的题可以试试简单思路。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值