codeforces C. 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 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.

思路:每次删除一些数,让删除了这些数之后,剩下的数能够是平方数,即x^2=y这种。因为数最大为2*10^9,只有10位,所以只用枚举10位数,把所有的可能枚举出来,然后转化为数字,再判断是否为平方数。

代码:

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
char str[100];
int len,ans=100,p;
ll cal(char temp[])
{
    ll sum=0;
    int l=strlen(temp),i=0;
    while(temp[i]=='0') ///不能有前导0
    {
        i++;
        p++;
    }
    for(; i<l; ++i) ///把字符串转化为整数
    {
        sum=sum*10+(temp[i]-'0');
    }
    return sum;
}
void print_subset(int n,int s)
{
    int cnt=0;
    char temp[100];
    p=0;
    for(int i=0; i<n ; ++i) ///枚举n位
    {
        if(s&(1<<i)) ///检测第i位上是否为1
        {
            //printf("%d ",i);
            temp[cnt++]=str[i];
        }
    }
    //printf("ss\n");
    temp[cnt]='\0';
    ll x=cal(temp);
    ll temp_n=(ll)sqrt(x);
    if(temp_n*temp_n==x && x!=0) ///判断是否可以平方
    {
        ans=min(ans,len-cnt+p);
    }
}
int main()
{
    gets(str);
    len=strlen(str);
    for(int i=1; i<(1<<len) ; ++i) ///枚举len个位置,需要1<<len,即有2^len种情况
    {
        //printf("%d %d\n",len,i);
        print_subset(len,i);
    }
    if(ans==100) ///没有满足的情况,即ans没有值变化
    {
        puts("-1");
    }
    else
        cout<<ans<<endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值