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.
The first line contains a single integer nn (1≤n≤2⋅1091≤n≤2⋅109). The number is given without leading zeroes.
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.
8314
2
625
0
333
-1
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.
思路:每次删除一些数,让删除了这些数之后,剩下的数能够是平方数,即x^2=y这种。因为数最大为2*10^9,只有10位,所以只用枚举10位数,把所有的可能枚举出来,然后转化为数字,再判断是否为平方数。
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
char str[100];
int len,ans=100,p;
ll cal(char temp[])
{
ll sum=0;
int l=strlen(temp),i=0;
while(temp[i]=='0') ///不能有前导0
{
i++;
p++;
}
for(; i<l; ++i) ///把字符串转化为整数
{
sum=sum*10+(temp[i]-'0');
}
return sum;
}
void print_subset(int n,int s)
{
int cnt=0;
char temp[100];
p=0;
for(int i=0; i<n ; ++i) ///枚举n位
{
if(s&(1<<i)) ///检测第i位上是否为1
{
//printf("%d ",i);
temp[cnt++]=str[i];
}
}
//printf("ss\n");
temp[cnt]='\0';
ll x=cal(temp);
ll temp_n=(ll)sqrt(x);
if(temp_n*temp_n==x && x!=0) ///判断是否可以平方
{
ans=min(ans,len-cnt+p);
}
}
int main()
{
gets(str);
len=strlen(str);
for(int i=1; i<(1<<len) ; ++i) ///枚举len个位置,需要1<<len,即有2^len种情况
{
//printf("%d %d\n",len,i);
print_subset(len,i);
}
if(ans==100) ///没有满足的情况,即ans没有值变化
{
puts("-1");
}
else
cout<<ans<<endl;
return 0;
}