HDU4394(数论中的广搜)

本文探讨了一个特定的数字平方模运算问题,并提供了一种高效的算法解决方案。通过从低位向高位进行广搜,该算法能快速找到满足条件的最小非负整数M,使得(M^2 % 10^y = N % 10^y)。文中详细解释了算法的实现过程,包括初始化、长度获取和核心搜索逻辑,旨在为解决类似数学问题提供一种实用的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:Digital Square

 

题意:

Given an integer N,you should come up with the minimumnonnegative integer M.M meets the follow condition: M2%10x=N (x=0,1,2,3....)
 
 

从低位向高位广搜,如果当前情况满足M^2 % 10^y = N % 10^y,则继续向下搜索。


#include <cstdio>
#include <cstring>
#include <queue>
#include <algorithm>
using namespace std;
const __int64 INF = 100000000000LL;

struct Node
{
    __int64 m, x;
    Node()
    {
        m = 0;
        x = 0;
    }
};

__int64 ten[10];

void init()
{
    __int64 num = 1;
    for(int i=0;i<10;++i)
    {
        ten[i] = num;
        num *= 10;
    }
}

int getLength(__int64 x)
{
    if(x == 0) return 1;
    int len = 0;
    while(x > 0)
    {
        x /= 10;
        ++ len;
    }
    return len;
}

int main()
{
    int caseNumber;
    __int64 n;
    init();
    scanf("%d", &caseNumber);
    while(caseNumber--)
    {
        scanf("%I64d", &n);
        int len = getLength(n);
        queue<Node> q;
        q.push(Node());
        while(!q.empty())
        {
            Node u = q.front();
            if(u.x == len) break;
            for(int i=0;i<10;++i)
            {
                Node v;
                v.m = u.m + ten[u.x] * i;
                v.x = u.x + 1;
                if((v.m * v.m) % ten[v.x] == n % ten[v.x]) q.push(v);
            }
            q.pop();
        }
        __int64 ans = INF;
        while(!q.empty())
        {
            Node node = q.front();
            if(ans > node.m)
                ans = node.m;
            q.pop();
        }
        if(ans == INF) printf("None\n");
        else           printf("%I64d\n", ans);
    }
    return 0;
}


 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值