网上找到一个用同余做的,觉得写的不错,地址
#include <cstdio>
#include <cstring>
#include <queue>
#include <iostream>
using namespace std;
const int maxn = 200;
queue<int> Q;
bool visit[maxn];
long long a[maxn];
void bfs(int n)
{
while (!Q.empty())
Q.pop();
memset(visit, false, sizeof(visit));
Q.push(1);
a[1] = 1;
visit[1] = true;
while (!visit[0])
{
int now = Q.front();
Q.pop();
int left = (now * 10) % n;
int right = (left + 1) % n; // not left + 1
if (!visit[left])
{
Q.push(left);
visit[left] = true;
a[left] = a[now] * 10;
}
if (!visit[right])
{
Q.push(right);
visit[right] = true;
a[right] = a[now] * 10 + 1;
}
}
printf("%lld\n", a[0]);
}
int main()
{
int n, now;
while (scanf("%d", &n) != EOF)
{
if (n == 0)
break;
bfs(n);
}
}
数组a记录的是结果,用同余做搜索,缩小了空间,根据结果判断是否为结束,想法不错。