ACM刷题之Codeforces————Make a Square

给定一个正整数 nn,不包含前导零。每次操作可以删除一个数字,使得结果仍为正整数且无前导零。找出使 nn 成为某个正整数平方所需的最少操作数,或报告不可能。如果不可能将 nn 转换为正整数的平方,则输出 -1。例如,8314 经过删除 3 和 4 后变成 8181,即 99 的平方。对于 333333,无法变为正整数的平方,所以答案是 -1。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


用暴力深搜就好了.

下面是ac代码:

#include<bits/stdc++.h>
using namespace std;
#define MID(x,y) ((x+y)>>1)
#define CLR(arr,val) memset(arr,val,sizeof(arr))
#define FAST_IO ios::sync_with_stdio(false);cin.tie(0);
const double PI = acos(-1.0);
const int INF = 0x3f3f3f3f;
const int N=2e5+7;
int le,i, j ,k, e;
char c[100];

void dfs(int x, int val, int step) {
	int b = c[x] - '0';
	if (x == le - 1) {
		//走到底
		int c = sqrt(val);
		if (c * c == val && val != 0) {
			e = min(step + 1, e);
		} 
		val = val*10 + b;
		c = sqrt(val);
		if (c * c == val && val != 0) {
			e = min(step, e);
		} 
		
		return ;
	}
	if (b != 0 || val != 0) {
		dfs(x + 1, val * 10 + b, step);
	}
	dfs(x + 1, val, step + 1);
	
}

int main()
{
	//freopen("f:/input.txt", "r", stdin);
	cin>>c;
	le = strlen(c);
	e = INF;
	dfs(0, 0, 0);
	if (e == INF) {
		cout<<-1<<endl;
		return 0;
	}
	cout<<e<<endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值