Digital Square(分支限界法)

A - Digital Square
HDU - 4394

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

解析:
dbook储存不同位的位权。
node里cur表示当前符合题目要求的数,len表示当前符合要求的数的位数,digit表示继续尝试的数。
优先队列实现的最终结果与结构体中的排序函数结果恰好相反。
从个位开始,按照以cur升序加入到优先队列中。如果对于某个数作为个位成立,则会将该数所属结构体额外加入队列,并下一次读取到该结构体时,将以该数为个位的数的十位从0到9进行遍历,选择符合条件的数。
……
以此类推,一直到可以完全匹配n并返回ans的值。如果ans为0说明无法匹配n,否则ans即为结果。

代码:

#include <iostream>
#include <cstdio>
#include <queue>

using namespace std;

typedef unsigned long long ULL;

const int MAX=18;
const int MAXDIGIT=9;

struct Node{
    ULL cur;
    int len;
    int digit;

    Node(){}
    Node(ULL c,int l,int d):cur(c),len(l),digit(d){}

    bool operator < (const Node a) const
    {
        return cur>a.cur;
    }
};

ULL dbook[MAX];
int n,nlen;
ULL ans;

void bfs()
{
    priority_queue<Node> q;
    Node now,next;

    int tem=n;
    nlen=0;
    while(tem)
    {
        nlen++;
        tem/=10;
    }

    ans=0;
    q.push(Node(0,0,0));

    while(!q.empty())
    {
        now=q.top();
        q.pop();

        if(now.len==nlen)
        {
            ans=now.cur;
            break;
        }
        else if(now.digit!=MAXDIGIT)
            q.push(Node(now.cur,now.len,now.digit+1));

        next.cur=now.cur+now.digit*dbook[now.len];
        next.len=now.len+1;
        next.digit=0;

        if(next.cur*next.cur%dbook[next.len]==n%dbook[next.len])
            q.push(next);
    }
}

int main()
{
    int t;

    dbook[0]=1;
    for(int i=1;i<MAX;i++)
        dbook[i]=dbook[i-1]*10;

    scanf("%d",&t);

    while(t--)
    {
        scanf("%d",&n);

        bfs();

        if(ans)
            printf("%llu\n",ans);
        else
            printf("None\n");
    }

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值