Codeforces-962C-Make a Square(暴力二进制枚举)

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 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 n to make from it the square of some positive integer or report that it is impossible.

An integer x is the square of some positive integer if and only if x=y2 for some positive integer y.

Input

The first line contains a single integer n(1n2109). The number is given without leading zeroes.

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 8314the digits 3 and4. After that8314 become equals to 81, which is the square of the integer 9.

In the second example the given 625is the square of the integer 25, so you should not delete anything.

In the third example it is impossible to make the square from 333, so the answer is -1.


题意:稳最少去掉几个数字使剩下的数字是个完全平方数;

思路:最多10位,用二进制枚举,从1<<(len)-1开始,len是整数的位数,一直到0就可以遍历出每一种情况,二进制的1表示改为保留,0表示去掉,然后每个判断一下就行;

AC代码:

#include<bits/stdc++.h>
using namespace std;
int n,a[15];
int init(int x)
{
    int cnt=0;
    while(x){
        a[++cnt]=x%10;
        x/=10;
    }
    return cnt;///位数
}
int main()
{
    cin>>n;
    int len=init(n);
    int ans=100;
    for(int i=(1<<len)-1;i>=0;i--){
        int tmp=0,cnt=0,flag=1;
        for(int j=len-1;j>=0;j--){
            if((i>>j)&1){
                cnt++;///记录有多少个1
                tmp=tmp*10+a[j+1];
                if(tmp==0){
                    flag=0;
                    break;
                }
            }
        }
        if(tmp&&flag&&(int(sqrt(tmp))*int(sqrt(tmp))==tmp)){
            ans=min(ans,len-cnt);
        }
    }
    if(ans!=100) printf("%d\n",ans);
    else  printf("-1\n");
    return 0;
}


猜你喜欢

转载自blog.csdn.net/qq_37171272/article/details/79904177