bfs很奇特的应用 膜拜大神。。。。。。
题目:给出n,求出最小的m,满足m^2 % 10^k = n,其中k=0,1,2
http://acm.hdu.edu.cn/showproblem.php?pid=4394
只要有一个x满足条件便行了
我们可以初步发现,某个数个位确定,那么平方的最后一位肯定是确定的,那么如果后两们确定,那么平方的最后两们也是确定的,这可以通过乘法的规律得到
那我们只需要BFS一下,不断地找满足最后指定位数的数,1位,2位,……直到找到第一个满足条件的。
#include<cstdio>
#include<queue>
using namespace std;
typedef __int64 ll;
ll fac[11];
struct Node
{
ll v;
int len;
bool operator < (Node p)const
{
return p.v<v;
}
};
void bfs(ll a)
{
priority_queue<Node> q;
Node temp,now;
temp.v=0;
temp.len=0;
q.push(temp);
int i;
while(!q.empty())
{
temp=q.top();
q.pop();
if((temp.v*temp.v)%fac[temp.len]==a)
{
printf("%I64d\n",temp.v);
return ;
}
for(i=0;i<=9;i++)
{
now.len=temp.len+1;
now.v=temp.v+i*fac[temp.len];
if((now.v*now.v)%fac[temp.len+1]==a%fac[temp.len+1])
{
q.push(now);
}
}
}
printf("None\n");
}
int main()
{
int i;
fac[0]=1;
for(i=1;i<11;i++)
{
fac[i]=10*fac[i-1];
}
int T;
scanf("%d",&T);
ll a;
while(T--)
{
scanf("%I64d",&a);
bfs(a);
}
return 0;
}