我是靠谱客的博主 积极热狗,最近开发中收集的这篇文章主要介绍hdu 4394 - Digital Square (dfs or bfs)Digital Square,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
题目:
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-14
const 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-14
const 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;
}
最后
以上就是积极热狗为你收集整理的hdu 4394 - Digital Square (dfs or bfs)Digital Square的全部内容,希望文章能够帮你解决hdu 4394 - Digital Square (dfs or bfs)Digital Square所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复