Given an integer N,you should come up with the minimum nonnegative integer M.M meets the follow condition: M ^2%10 ^x=N (x=0,1,2,3…)
Input
The first line has an integer T( T< = 1000), the number of test cases.
For each case, each line contains one integer N(0<= N <=10 9), indicating the given number.
Output
For each case output the answer if it exists, otherwise print “None”.
Sample Input
3
3
21
25
Sample Output
None
11
5
需要找一个满足条件的最小的M使其等式成立,考得是DFS,需要从最后一位开始找,满足条件就入队,直到符合条件为止,不然输出None。代码参考网上大神的,侵删。
#include<iostream>
#include<stdio.h>
#include<queue>
using namespace std;
struct Node{
long long int num;
long long int t;
friend bool operator < (Node a,Node b)
{
return a.num>b.num;//用到优先队列来符合最小,需要重载运算符
}
};
struct Node x,y;
void bfs(int n,int flag)
{
priority_queue<Node>q;
for(int i=0;i<10;i++)
{
if(i*i%10==n%10)
{
x.num=i;
x.t=10;
q.push(x);//寻找符合条件的个位数
}
}
while(!q.empty())
{
x=q.top();
if(x.num*x.num%flag==n)
{
cout<<x.num<<endl;
return ;
}
q.pop();
for(int i=0;i<10;i++)
{
y.num=x.num+i*x.t;
y.t=x.t*10;
if(y.num*y.num%y.t==n%y.t)
q.push(y); //在所有符合条件的数中继续搜索符合条件就入队
}
}
cout<<"None"<<endl;
}
int main()
{
int t,n,flag;
cin>>t;
while(t--)
{
cin>>n;
flag=1;
int temp=n;
while(temp)
{
flag*=10;
temp/=10;
}
bfs(n,flag);
}
return 0;
}