Find The Multiple POJ - 1426

这道题有点坑啊。这道题我首先想到的思路就是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. 对这种数据坑的题可以试试简单思路。

猜你喜欢

转载自blog.csdn.net/sunmaoxiang/article/details/80865883