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 nhtml

, written without leading zeroes (for example, the number 04 is incorrect). git

In one operation you can delete any digit of the given integer so that the result remains a positive integer without leading zeros.app

Determine the minimum number of operations that you need to consistently apply to the given integer nide

to make from it the square of some positive integer or report that it is impossible.ui

An integer xatom

is the square of some positive integer if and only if x=y2 for some positive integer yspa

.code

Input

The first line contains a single integer nxml

(1n2109htm

). 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\n",ans);
    return 0;
}
View Code
相關文章
相關標籤/搜索