Description
You are given a positive integer n , written without leading zeroes (for example, the number 04 is incorrect).
In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros.
Determine the minimum number of operations that you need to consistently apply to the given integer
An integer
x
is the square of some positive integer if and only if
Input
The first line contains a single integer
Output
If it is impossible to make the square of some positive integer from n, print -1. In the other case, print the minimal number of operations required to do it.
Examples
Input |
---|
8314 |
Output |
2 |
Input |
---|
625 |
Output |
0 |
Input |
---|
333 |
Output |
-1 |
Note
In the first example we should delete from
8314
the digits
3
and
In the second example the given
In the third example it is impossible to make the square from 333 , so the answer is −1 .
参考了下面的博客
题意:给一个整数,每次删除一个位,要求删除后的首位不能是0,问多少次操作以后变为平方数。
思路:百度了一下开方函数的复杂度,没有看的很懂但是其中有一个说法是:
- 取对数->乘0.5->取指数
其中第一步和第三步可以用硬件实现,这样下来复杂度就是O(1)的,所以用开方函数来检查一个整数是否是平方数是可以的。
由于输入最多有10位,搜索起来最坏的情况要做10!次,这是不能接受的,这是由于重复搜索导致的,所以使用set记录搜索过的数字,把次数降到了2^10次(巨大的优化)
#include<stdio.h>
#include<math.h>
#include<queue>
#include<set>
using std::queue;
using std::set;
#define max(a,b) ((a)>(b)?(a):(b))
#define min(a,b) ((a)<(b)?(a):(b))
#define mabs(x) ((x)>0?(x):(0-(x)))
#define N_max 44722
int n;
int a10[N_max];
queue<int> a;
set<int> b;
int r(int x, int i) {
return x / a10[i + 1]*a10[i] + x%a10[i];
}
int bfs(int len) {
int next,temp;
for (int k = 0; k < len; ++k) {
int t = a.size(), x;
for (int i = 0; i < t; ++i) {
//遍历上一层产生的数
x = a.front(); a.pop();
for (int q = 0; q < len - k; ++q) {//搜索去掉每一位后产生的数
if (q>0&&q ==len-k-1 && ((x%a10[q]) / a10[q - 1]) == 0)
//判断是否在首位以及同时第二位是否是0
continue;
next = r(x, q);//生成下一个数
if (next <= 0)continue;//特判
//利用set检查该数是否出现过
if (b.find(next) == b.end())b.insert(next);
else { continue; }
//利用sqrt检查该数是否是平方数
temp = sqrt(next);
if (temp*temp == next)
return k;
//入队列,为下一层bfs做准备
a.push(next);
}
}
}
}
int main() {
scanf("%d", &n);
int len = 0,temp;
temp = sqrt(n);
if (temp*temp == n) {
printf("0"); return 0;
}
//计算位数,保存在len里
for (temp = n; temp > 0; ++len)temp /= 10;
//计算10, 100, 1000,...方便取模
a10[0] = 1;
for (int i = 1; i < 15; ++i) {
a10[i] = a10[i - 1] * 10;
}
a.push(n);
temp = 1 + bfs(len);
if(temp<len)printf("%d",temp);
else printf("-1");
}