題目:
給定一個正整數N,求一個最小的正整數M(M>1),是的M*N的十進制表示中只含有1和0,
分析可以得到,滿足十進制表示中只含有0和1的數:1,10,11,100,101,110,111……
所以可以依次用這些數做測試
代碼來自:點擊打開鏈接
#define _CRT_SECURE_NO_WARNINGS 1
#include <cstdio>
#include <queue>
using namespace std;
int main() {
int N;
while (scanf("%d", &N) != EOF) {
queue<int> q;
q.push(1);
while (!q.empty()) {
int t = q.front();
q.pop();
if (t % N == 0) {
printf("n = %d, m = %d, n*m = %d/n", N, t / N, t);
break;
}
q.push(t * 10);//構造1,10,11,100,101,110,111……序列
q.push(t * 10 + 1);
}
}
return 0;
}
還有就是在一個循環節內,餘數相同的數他們可以進行只計算一次,因爲它們的是重複的。因此可以把餘數存下來過濾掉一些冗餘的計算
// 解法四:將搜索空間分過類的廣度搜索,這樣空間佔用是O(N)而不是
// 指數級。分類的原則是按照模N的餘數分類
#define _CRT_SECURE_NO_WARNINGS 1
#include <cstdio>
#include <bitset>
#include <vector>
#include <queue>
using namespace std;
struct QNode {
int v, r; // v is value, r is remainder
QNode(int vv, int rr) : v(vv), r(rr) {}
QNode() : v(0), r(0) {}
};
int main() {
int N;
while (scanf("%d", &N) != EOF) {
//bitset<N> bn;
queue<QNode> q;
q.push(QNode(1, 1));
while (!q.empty()) {
//bn.reset();
vector<bool> bn(N, false); //存儲餘數是否存在,存在爲true
int s = q.size();
while (s--) {
QNode t = q.front();
if (t.r == 0) {
printf("n = %d, m = %d, n*m = %d/n", N, t.v / N, t.v);
goto ok;
}
q.pop();
if (!bn[t.r * 10 % N]) {//如果爲false表示這個餘數裏面沒有,則對其進行存儲,如果已經存在,在當前循環節內,不在進行計算
bn[t.r * 10 % N] = true;
q.push(QNode(t.v * 10, t.r * 10 % N));
}
if (!bn[(t.r * 10 + 1) % N]) {
bn[(t.r * 10 + 1) % N] = true;
q.push(QNode(t.v * 10 + 1, (t.r * 10 + 1) % N));
}
}
}
ok:;
}
return 0;
}