zoukankan      html  css  js  c++  java
  • 【洛谷P2841】A*B Problem【bfs】【高精度】

    题目大意:

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


    思路:

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


    代码:

    #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
    ");
    	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;
    }
    
  • 相关阅读:
    【链表】Bzoj1098[POI2007]办公楼biu
    【构造】Bzoj1432[ZJOI2009]Function
    【Dp】Bzoj1296 [SCOI2009] 粉刷匠
    【二分贪心】Bzoj3969 [WF2013] Low Power
    【递推】Bzoj3612[Heoi2014]平衡
    HDU-3718 Similarity
    HDU-3435 A new Graph Game
    HDU-3488 Tour
    HDU-1853 Cyclic Tour
    HDU-1533 Going Home
  • 原文地址:https://www.cnblogs.com/hello-tomorrow/p/11998127.html
Copyright © 2011-2022 走看看