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

版权声明:本文为小时的枫原创文章,未经博主允许不得转载。 https://blog.csdn.net/xiaofeng187/article/details/79903590
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;
}

猜你喜欢

转载自blog.csdn.net/xiaofeng187/article/details/79903590