题目链接:点击打开链接
题目描述:
C. Make a Square
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output
You are given a positive integer nn, 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 nn to make from it the square of some positive integer or report that it is impossible.
An integer xx is the square of some positive integer if and only if x=y2x=y2 for some positive integer yy.
Input
The first line contains a single integer nn (1≤n≤2⋅1091≤n≤2⋅109). The number is given without leading zeroes.
Output
If it is impossible to make the square of some positive integer from nn, print -1. In the other case, print the minimal number of operations required to do it.
Examples
Input
Copy
8314
Output
Copy
2
Input
Copy
625
Output
Copy
0
Input
Copy
333
Output
Copy
-1
Note
In the first example we should delete from 83148314 the digits 33 and 44. After that 83148314 become equals to 8181, which is the square of the integer 99.
In the second example the given 625625 is the square of the integer 2525, so you should not delete anything.
In the third example it is impossible to make the square from 333333, so the answer is -1.
题意:给你一个大小在1到2e9的数,问能否删去部分数字,使这个数成为一个平方数,若能,则输出最少需要删除多少个数字使得原来的数成为一个平方数,否则输出-1。
分析:拿到题目看到数据范围:n最大2e9,因此直接大暴力估计会超时。然而因为题目要求是要删除位数,故联想到数位dp。先存储每一位的数字,然后进行dfs记录最小操作数即可。
#include <bits/stdc++.h>
#define maxn 10005
using namespace std;
const int INF=0x3f3f3f3f;
int bit[maxn],res;//bit数组存储位数,res记录结果
int cnt=0;//统计总位数大小
void getbit(int x){//获取一个数上各个位上的数字
while(x){
bit[++cnt]=x%10;
x/=10;
}
}
void dfs(int x,int num,int lowbit)//x代表枚举个数,num代表当前的数,lowbit代表当前的位数
{
int tmp=num;
int cntt=0;//当前的数的位数
while(tmp) tmp/=10,cntt++;//获取当前数的位数
int q=sqrt(num);//求当前的开根
if(num==q*q) res=min(cnt-cntt,res);//判断是否满足平方数,如果是,记录位数差的最小值
if(lowbit>=cnt) return;//如果当前的位数大于总位数,返回
for(int i=lowbit+1;i<=cnt;i++) //从当前位数枚举到总位数
dfs(x+1,num*10+bit[i],i);//不断递归下去求解
}
int main(){
//startcoding
int n;
cin>>n;//输入数
getbit(n);//获取位数
res=INF;//初始值赋予INF
reverse(bit+1,bit+1+cnt);//bit数组所存储的位数与实际位数相反,因此要反转一下
dfs(1,0,0);//dfs统计答案
if(res==cnt) puts("-1"); //如果答案数刚好等于总位数,则不存在
else cout<<res<<endl;//否则输出答案
return 0;
}