题目链接: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;
}