CF962C Make a Square(BFS)

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
Copy
8314
Output
Copy
2
Input
Copy
625
Output
Copy
0
Input
Copy
333
Output
Copy
-1

分析:BFS,暴力出奇迹=_=......

#include<cstdio>
#include<cstring>
#include<algorithm>
#include<queue>
#include<map>
#include<cmath>
using namespace std;
long long N;
long long a[19];
map<long long,int> m;
struct Node{
    long long x;int num;
};

int bfs()
{
    int ans=999999999;
    Node s;s.num=0;s.x=N;
    queue<Node> q;
    q.push(s);
    while(!q.empty())
    {
        Node u=q.front();q.pop();
        if(u.num>=ans) continue;
        long long n=u.x;
        long long temp=(long long)sqrt(n);
        
        if(temp*temp==n) 
        {
            ans=min(ans,u.num);
            continue;
        }
        if(m[n]==1) continue;
        m[n]=1;
        int i;
        for(i=1;i<=12;i++)
        {
            if(n<a[i]) break;
            else
            {
                long long temp=(n/a[i])*a[i-1]+n%a[i-1];
//从右到左依次去掉每位的数字 
                if(temp>0)
                {
                    Node p;
                    p.num=u.num+1;p.x=temp;
                    q.push(p);
                }
            }
        }
        if(i>=2&&(n/a[i-2])%10==0) continue;
        //排除从左到右数第2位是0的情况(就是去掉第一位后有前导0的情况) 
        temp=n%a[i-1];//去掉第一位 
        if(temp>0)
        {
            Node p;
            p.num=u.num+1;p.x=temp;
            q.push(p);
        }
    }
    if(ans!=999999999) return ans;
    return -1;
}

int main()
{
    a[0]=1;
    for(int i=1;i<=11;i++)
    a[i]=a[i-1]*10;
    scanf("%lld",&N);
    int ans=bfs();
    printf("%d
",ans);
    return 0;
}
View Code
原文地址:https://www.cnblogs.com/ACRykl/p/8823394.html