CodeForces 962C - Make a Square

题目链接:http://codeforces.com/contest/962/problem/C

题意:给你一个数字n (n<=2e9)没有前导0。现在需要你删除一些数字,也可以不删除,使得剩下的数是平方数。删除后得到的数字不存在前导0。输出删除最少的位数,不存在输出-1.

两种思路。
一种是位运算暴力枚举可能的情况,共2^cnt种(cnt为位数),用1~2^cnt的二进制数表示出来,0表示删除,1不删。再判断是否为平方数。
第二种,枚举平方数,然后都转成字符串,比一下两个字符串能否满足题意,如满足则两个字符串位数一减。

经测试后一种方法时间是前一种的6~7倍。

如何判断平方数我一开始尝试打表+二分查找,其实没那么复杂,直接sqrt(n) = i,然后判断i*i==n即可。

思路一

#include<bits/stdc++.h>

using namespace std;

int b[15];
long long qw[15];
long long n,d;
int cnt;
int p=100;
int main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    qw[0]=1;
    for(int i=1;i<=10;i++){
        qw[i]=qw[i-1]*10;
    }
    cin>>n;
    d=n;
    cnt=0;
    while(d){
        b[cnt]=d%10;
        d/=10;
        cnt++;
    }
    int up=pow(2,cnt);
    for(int i=1;i<up;i++){
        int ans=0;
        long long sum=0;
        for(int j=0;j<cnt;j++){
            if(1&(i>>j)){
                sum+=b[j]*qw[ans];
                ans++;
            }
        }
        long long sb=sqrt(sum);
        if(sb*sb==sum&&sum>=qw[ans-1]){
            p=min(p,cnt-ans);
        }
    }
    if(p==100){
        cout<<-1<<endl;
    }
    else cout<<p<<endl;
return 0;
}

思路二

#include <bits/stdc++.h>
#define show(a) cout << #a << " = " << a << endl;
const int MOD = 1e9+7;
const int MAXN = 10005;

using namespace std;

int main()
{
    std::ios::sync_with_stdio(false);
    int n;
    cin >> n;
    string str,t;
    t = to_string(n);
    int ans = 100;
    for (int i = 1; i * i <= n; i++)
    {
        str = to_string(i*i);
        int mstr = 0, mt = 0;
        while (mt < t.size())
        {
            if (mt < t.size() && mstr < str.size() && t[mt] == str[mstr])
            {
                mstr++;mt++;
            }
            else
                mt++;
        }
        if (mstr == str.size())
            ans = t.size() - str.size();

    }
    if (ans == 100)
        cout << -1 << endl;
    else
        cout << ans << endl;
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值