您的位置:首页 > 其它

hdu 4394 Digital Square(搜索:DFS)

2014-08-18 09:32 495 查看
用BFS写了好久,总是WA, 看了别人的DFS如下:

如我们的n == 21; 那么,我们从个位数1开始搜, 1 * 1 == 1, 9 * 9 == 81,他们的个位数都是1,那么,1和9可以作为我们找的那个数的个位数。

然后我们就记忆一下这个我们找到的东西,放在ans里面。

下面我们开始搜第二位,设搜的是ab的a(其中,我们的b是已经记忆下来的个位)。

ab * ab % 100 = 21; 那么,我们的2 是不是就由(b * b / 10 + a * b * 2) % 10 得到的。于是,我们就for一遍去找a,找到a了,我们就以同样的方法去找c(如果有c的话)。这样,就是剪枝了。

最后,如果我们找的n有x位,那么,我们要找的m * m % ? == n 的m最多也只有x位。至此,就结束了。

代码如下:

#include <cstdio>
#include <iostream>
#include <algorithm>
#define LL long long
#define INF 0x7fffffff
using namespace std;

LL ans, rem, cnt;
int digit[20];

void get_digit(LL n) {
cnt = 0;
while(n) {
digit[++cnt] = n%10;
n /= 10;
}
}

void dfs(LL pos, LL w, LL tmp) {
if(cnt < pos) {
ans = min(ans, tmp);
return ;
}
for(LL k=0; k<10; ++k) {
if((tmp*tmp/w+rem*k%10)%10 == digit[pos])
dfs(pos+1, w*10, k*w+tmp);
}
}

int main(void) {
LL T, n;
cin >> T;
while(T--) {
cin >> n;
ans = INF;
get_digit(n);
for(LL i=0; i<10; ++i) {
if(i*i%10 == digit[1]) {
rem = i<<1;//rem==2b;
dfs(2, 10, i);
}
}
if(ans != INF)
cout << ans << endl;
else cout << "None" << endl;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: