【洛谷P2841】A*B Problem【bfs】【高精度】

题目大意:

题目链接:https://www.luogu.org/problemnew/show/P2841
给出一个数 A A ,你需要给出一个最小的数 B B ,使得 A A B B 的乘积只含有0和1。


思路:

全部运算用高精度不解释。
显然暴力枚举二进制数是会超时的。因为枚举时会枚举到很多完全没必要算的数。
x x y y 两个01数满足 x y ( m o d   n ) x\equiv y(mod\ n) x < y x<y ,那么在 x x y y 末尾再加上一个0或1,这两个数 m o d   n mod\ n 也是同余的。这样的话大的数字 ( y ) (y) 就完全没有必要枚举,前缀为 y y 的数字也不需要枚举了。因为总有一个比它小的数字和它同余,而我们要求的是最小的答案。
所以可以用 b f s bfs 来枚举01数,先枚举0,再枚举1,这样就可以保证枚举出来的01数是按从小到大的顺序来枚举的。同时用 h a s h hash 来判断余数(直接用数组即可。 n 1 0 4 n\leq 10^4 ),如果已经有一个数和这个数的余数相同,那么这个数就不用继续往下枚举了。
找到答案就直接退出 b f s bfs ,因为我们在搜索的时候已经保证了答案尽量小。
然后就高精除单精算出第一个答案,第二个答案就是 a n s ans


代码:

#include <queue>
#include <cstdio>
using namespace std;

const int N=10010,M=200;
int n,a[N];
bool hash[N],flag;

struct node
{
	int a[M+1],p,len;
}ans1,ans2;
queue<node> q;

node xx;
void bfs()
{
	xx.len=1; xx.a[1]=1; xx.p=1; q.push(xx);
	hash[1]=1;
	while (q.size())
	{
		node u=q.front();
		q.pop();
		if (!u.p)
		{
			ans1=ans2=u;
			return;
		}
		for (int i=0;i<=1;i++)
		{
			int p=(u.p*10+i)%n;
			if (!hash[p])
			{
				hash[p]=1;
				node v=u;
				v.len++;
				v.a[v.len]=i;
				v.p=p;
				q.push(v);
			}	
		}
	}
}

int main()
{
	scanf("%d",&n);
	if (n==1) return !printf("1 1\n");
	bfs();
	for (int i=1;i<=ans1.len;i++)
	{
		a[i]=ans1.a[i]/n;
		ans1.a[i+1]+=ans1.a[i]%n*10;
	}
	int i=1;
	while (!a[i]) i++;
	for (;i<=ans2.len;i++) printf("%d",a[i]);
	putchar(32);
	for (i=1;i<=ans2.len;i++) printf("%d",ans2.a[i]);
	return 0;
}

猜你喜欢

转载自blog.csdn.net/SSL_ZYC/article/details/94710122