codeforces 962 C. Make a Square

本文介绍了一个算法问题,即如何通过删除数字将一个正整数变为完全平方数,并给出了解决方案。文章详细解释了输入输出格式及示例,提供了一段C++代码实现。
time limit per test : 2 seconds
memory limit per test : 256 megabytes
input : standard input
output : standard output

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.

Input

The first line contains a single integer nn (1n21091≤n≤2⋅109). The number is given without leading zeroes.

Output

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.

Examples
input
Copy
8314
output
Copy
2
input
Copy
625
output
Copy
0
input
Copy
333
output
Copy
-1
Note

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.

这个最多只有10位。。。。

代码:

#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cstring>
#define ll long long
using namespace std;
const int maxn = 1e5+7;
ll INF = 1e8+7, t;

string s;
vector<ll> a;


bool solve()
{
    if(a.size() == 0) return false;
    else if(a[0] == 0) return false;
    else {
        ll res = 0;
        for(int i = 0; i < a.size(); i++)
        {
            res = res*10+a[i];
        }
        ll sres = sqrt(res);
        if(res == sres*sres) return true;
        else return false;
    }
}

int main()
{
    cin >> s;
    int n = s.length();
    ll len = 1<<n, res = INF;
    for(int i = 0; i <= len; i++)
    {
        a.clear();
        for(int j = 0; j < n; j++)
        {
            if(i>>j&1) a.push_back(s[j] - '0');
        }
        if(solve()) res = min(res, (ll)(n - a.size()));
    }
    if(res == INF) res = -1;
    printf("%d\n",res);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值