hdu 4394 - Digital Square (dfs or bfs)

来源:互联网 发布:德国电子地图软件 编辑:程序博客网 时间:2024/05/17 01:55

题目:

Digital Square

题意:

输入N,找到最小的M,使得M2%10x=N (x=0,1,2,3....)


思路:

%10x取的是最后几位,只有满足m*m%x == n%x,即先匹配后几位的数才可能向上匹配到n 。 明显的一个位数递推,dfs和bfs均可

要注意向上枚举最高位数时,是从0开始而非1开始,因为有可能一个数就可以直接匹配到n。


代码:

dfs:

//#pragma comment(linker, "/STACK:102400000,102400000")#include "iostream"#include "cstring"#include "algorithm"#include "cmath"#include "cstdio"#include "sstream"#include "queue"#include "vector"#include "string"#include "stack"#include "cstdlib"#include "deque"#include "fstream"#include "map"using namespace std;typedef long long LL;const long long LINF = (long long)1e30;const int INF = 522133279;const int MAXN = 100000+100;#define eps 1e-14const int mod = 100000007;LL n;LL minc;LL minll(LL a , LL b){    return a > b ? b : a;}void dfs(LL x , LL cur){    if(cur*cur%x == n)    {        minc = minll(minc,cur);        return;    }    for(int i = 0 ; i <= 9 ; i++)    {        LL tmp = i*x + cur;        if(tmp*tmp%x == n%x)            dfs(x*10 , tmp);    }}int main(){    //freopen("in","r",stdin);    //freopen("out","w",stdout);    int t;    scanf("%d",&t);    while(t--)    {        cin >> n;        minc = LINF;        dfs(1,0);        if(minc == LINF)            cout << "None" << endl;        else            cout << minc << endl;    }    return 0;}

bfs:

//#pragma comment(linker, "/STACK:102400000,102400000")#include "iostream"#include "cstring"#include "algorithm"#include "cmath"#include "cstdio"#include "sstream"#include "queue"#include "vector"#include "string"#include "stack"#include "cstdlib"#include "deque"#include "fstream"#include "map"using namespace std;typedef long long LL;const int INF = 522133279;const int MAXN = 1000000+100;#define eps 1e-14const int mod = 100000007;LL n;int ok;struct node{    LL data;    int x;    node()    {}    node(LL xx , int xxx) : data(xx) , x(xxx) {}    bool operator < (const node& b)const    {        return data > b.data;    }};void bfs(){    priority_queue<node> que;    node tmp,cur;    que.push(node(0,0));    while(!que.empty())    {        tmp = que.top();        que.pop();        LL p = (LL)pow(10.0, tmp.x);        if((tmp.data*tmp.data)%p == n)        {            cout << tmp.data << endl;            ok=1;            return;        }        for(int i = 0 ; i <= 9 ; i++)        {            cur.x = tmp.x+1;            cur.data = tmp.data + i*p;            if(cur.data*cur.data%(p*10) == n%(p*10))                que.push(cur);        }    }}int main(){    //freopen("in","r",stdin);    //freopen("out","w",stdout);    int t;    cin >>t;    while(t--)    {        ok=0;        cin >> n;        bfs();        if(!ok)            cout << "None" << endl;    }    return 0;}