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
解法一(不使用优先队列)
主要思想是一位一位的看
看每一位满足否遍历0~9
个位 满足看十位
M平方的个位由M的个位决定
M平方的十位由M的个位和十位决定
M平方的百位由M的个十百位决定
import java.util.Scanner;
import java.util.LinkedList;
import java.util.Queue;
class node{
long value;//M的值
long place;//10的x的平方的值
}
public class Main {
public static long n;
public static void bfs(){
node now=new node();
now.value=0;
now.place=1;
Queue<node> a=new LinkedList<node>();//队列
a.add(now);
long ans=0xfffffff;
boolean findans=false;
while(!a.isEmpty()){
now=a.peek();
a.poll();
for(int i=0;i<10;i++){
node nex=new node();//一定要new 一定否则队列中都是最后一个赋值
nex.place=now.place*10;//计算下一位
nex.value=now.value+i*now.place;//计算0~9是否满足n 21+1*100
if(nex.value*nex.value%nex.place-n%nex.place==0){//例如121%100==21%100
if(!findans){
a.add(nex);
}
if(nex.value*nex.value%nex.place==n&&nex.value<ans){//121%100==21
findans=true;
ans=nex.value;//取最小不再进队列
}
}
}
}
if(ans==0xfffffff){//没有满足的
System.out.println("None");
}else{
System.out.println(ans);
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
while(T>0){
n=sc.nextLong();
bfs();
T--;
}
}
}
解法2 (使用优先队列) 不用考虑排序最小的始终放在队列头
import java.util.Scanner;
import java.util.Comparator;
import java.util.LinkedList;
import java.util.Queue;
import java.util.PriorityQueue;
class node{
long value;
long place;
}
public class Main {
public static long n;
public static void bfs(){
node now=new node();
now.value=0;
now.place=1;
PriorityQueue<node> a=new PriorityQueue<node>(new Comparator<node>(){
public int compare(node x,node y){
return (int) (x.value-y.value);
}
});
a.add(now);
while(!a.isEmpty()){
now=a.peek();
a.poll();
if(now.value*now.value%now.place==n){
System.out.println(now.value);
return;
}
for(int i=0;i<10;i++){
node nex=new node();
nex.place=now.place*10;
nex.value=now.value+i*now.place;
if(nex.value*nex.value%nex.place==n%nex.place){
a.add(nex);
}
}
}
System.out.println("None");
}
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner sc=new Scanner(System.in);
int T=sc.nextInt();
while(T>0){
n=sc.nextLong();
bfs();
T--;
}
}
}