题目:
给定一个正整数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;
}