Digital Square

Digital Square

Given an integer N,you should come up with the minimum nonnegative integer M.M meets the follow condition: M2%10x=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 <=109), 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 = abc,即M = 100a+10b+c,则M2 = 1000a2 + 2000ab + 100(b2+2ac) + 20bc + c2。易知,M2的个位只与M的最后1位有关,M2的十位只与M的最后2位有关,M2的百位只与M的最后3位有关…
所以可以用广度优先搜索算法先从M的最后一位开始搜索,M2的个位只与M的最后一位有关,如果M2的个位与N的个位相等,则符合条件进行下一位的搜索…
代码:

#include<iostream>
#include<queue>
using namespace std;
typedef long long ll;
typedef struct num{
    ll value;
    ll mod;
    bool operator < (const num& b)const{
         return value>b.value;
    }
}num;
priority_queue<num>q;//使用优先队列,保证队首元素是队中最小元素
int f;//标记是否找到m满足条件
/*M = abc,即M = 100*a+10*b+c,则M2 = 10000*a*a + 1000*2*a*b + 100*(b*b+2*a*c) + 10*2*b*c + c*c。
易知,M*M的个位只与M的最后1位有关,M*M的十位只与M的最后2位有关,M*M的百位只与M的最后3位有关...*/
void bfs(ll n){
    f=0;
    num now,next;
    now.value=0;
    now.mod=1;
    q.push(now);
    while(!q.empty()){
        now=q.top();
        q.pop();
        //cout<<now.value<<" "<<now.mod<<endl;
        if((now.value*now.value)%now.mod==n){
            f=1;//找到满足条件的m,f=1
            cout<<now.value<<endl;
            return;
        }
        next.mod=now.mod*10;
        for(int i=0;i<=9;i++){
            next.value=now.value+i*now.mod;
            if((next.value*next.value)%(now.mod*10)==n%(now.mod*10)){
                q.push(next);
            }/*m的最后x位数字与m*m的相关位对应,如果m*m的相关位与n的相关位相对应,入队,搜素m的最后x+1位数字,
            如,如果取m的最后一位,该位与m*m的个位相关,如果此时m*m的
            个位与n的个位相同,则将进行m最后两位的判断,依次类推。*/
        }
    }
}
int main(void){
    ll t,n,m;
    cin>>t;
    while(t--){
        cin>>n;
        bfs(n);
        if(f==0){
            cout<<"None"<<endl;
        }
    }
    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值