cf Educational Codeforces Round 42 C. Make a Square

原题:
C. Make a Square
time limit per test2 seconds
memory limit per test256 megabytes
inputstandard input
outputstandard 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 x = y 2 for some positive integer y.

Input
The first line contains a single integer n (1≤n≤2×10^9). 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 8314 the digits 3 and 4. After that 8314 become equals to 81, which is the square of the integer 9.

In the second example the given 625 is 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.

中文:

给你一个数,让你去掉这个数的某几位数,是否能变成一个平方数,如果能,找出去掉最少多少位数。

代码:

#include
using namespace std;

typedef long long ll;
typedef bitset<10> B10;

ll n;
string s;


int b,ind;


ll del_bit(const B10 &B)
{
    string tmp="";
    for(int i=0;iif(!B[i])
            tmp+=s[i];
    }
    //cout<

    for(int i=0;iif(tmp[i]=='0')
        {
            if(i==0)
                return -1;
        }
    }


    return stoll(tmp);

}


int main()
{
    ios::sync_with_stdio(false);

    while(cin>>n)
    {

        int ans=INT_MAX;
        s=to_string(n);
        b=s.size();
        ind=(1<for(int i=0;i1;i++)
        {
            B10 tmp(i);
            res=del_bit(tmp);
            if(res==-1)
                continue;
            a=sqrt(res);
            if(a*a==res)
            {
                if(ans>tmp.count())
                    ans=tmp.count();
            }
        }
        if(ans==INT_MAX)
            ans=-1;
        cout<return 0;
}

解答:

暴力枚举即可,可以利用位运算来枚举去掉哪几位。

bitset比较好用。

你可能感兴趣的:(贪心\模拟\STL\暴力)