HDU4394 Digital Square(数学+bfs)

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^2 % 10^x =N,求满足条件的最小的M

思路:可以根据余数N求出10^x的值

          这样就相当于M的平方除以一个常数等于N

          最直接的就是从0然后往上便利,这样肯定会超时的

          所以就有思维在里边了--从i(0~9)可以先求出i*i的个位数等于N%10的数,放到优先队列中

          只有相等的时候才可能才有可能满足题目的要求,然后这时候枚举 

         eg:N=21,num=N%10=1,mod=100,对于0~9,只有1和9的时候i*i才会出现1,所以入优先队列

             然后开始枚举一位数,两位数三位数.......,比如11,21,31......;19,29........;

             如果满足条件r.x*r.x%r.y==n%r.y,就可以入队了,直到找到一个数%mod==n就success了

 

import java.util.PriorityQueue;
import java.util.Scanner;
//按照x从小到大排序
class node implements Comparable<node>{
	long x;
	long y;
	@Override
	public int compareTo(node o) {
		// TODO Auto-generated method stub
		return (int) ((int)this.x-o.x);
	}
}
public class Main {
   static long mod;
   static int n;
   static PriorityQueue<node> q=new PriorityQueue<>();
   public static void bfs(){
	   int num=n%10;
	   for(long i=0;i<10;i++){
		   if(i*i%10==num){
			   node s=new node();
			   s.x=i;
			   s.y=10;
			   q.offer(s);
		   }
	   }
	   boolean flag=false;
	   while(!q.isEmpty()){
		   node t=q.poll();
		   if(t.x*t.x%mod==n%mod){
			   System.out.println(t.x);
			   flag=true;
			   break;
		   }
		   for(int i=0;i<10;i++){
			   node r=new node();
			   r.x=t.x+i*t.y;//这里i是乘t.y,一开始乘以10了
			   r.y=t.y*10;
			   if(r.x*r.x%r.y==n%r.y){
				   q.offer(r);
			   }
		   }
	   }
	   if(!flag)
	     System.out.println("None");
   }
   public static void main(String[] args) {
	 Scanner scan=new Scanner(System.in);
	 int t=scan.nextInt();
	 while(t!=0){
		 n=scan.nextInt();
		 //先求出10^x的值
		 int nn=n;
		 mod=1;
		 while(nn!=0){
			 nn/=10;
			 mod*=10;
		 }
		 bfs();
		 t--;
	 }
}
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

小鱼爱吃火锅

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值