题意:给你一个数,问从中删除某几位数字后重新组成的数字是否是某个数的平方;

解题思路:数据小,dfs直接搜,每位数只有两种选择,要或者不要

#include<iostream>
#include<algorithm>
#include<cstring>
#include<cmath>
#define ll long long
using namespace std;
ll a[20];
int ans=999999;
int cnt;
void dfs(int step,ll x,int len)
{
    if(step>cnt)
        return;
    int m=sqrt(x);
    int tx=x;
    if(m*m==x&&x!=0)
    {
    	int t=0;
		while(tx)
		{
			t++;
			tx=tx/10;
		 } 
        ans=min(ans,cnt-t);
    }
    dfs(step+1,x,len);
    dfs(step+1,x+a[step+1]*pow(10,len),len+1);
}
int main()
{
    ll n;
    ll z;
    cnt=0;
    cin>>n;
    z=n;
    int q=sqrt(n);
    if(q*q==n)
        cout<<"0\n";
    else
    {

    while(z)
    {
        cnt++;
        a[cnt]=z%10;
        z=z/10;
    }
    dfs(0,0,0);
    if(ans==999999)
        cout<<"-1\n";
    else
        cout<<ans<<endl;
    }
}

  

转载于:https://www.cnblogs.com/huangdao/p/8799025.html

Logo

GitCode 天启AI是一款由 GitCode 团队打造的智能助手,基于先进的LLM(大语言模型)与多智能体 Agent 技术构建,致力于为用户提供高效、智能、多模态的创作与开发支持。它不仅支持自然语言对话,还具备处理文件、生成 PPT、撰写分析报告、开发 Web 应用等多项能力,真正做到“一句话,让 Al帮你完成复杂任务”。

更多推荐