SSLOJ 1460.逛机房【bfs】


题意:

给出 T T T个数,对于每个数我们都有两种操作:
1. 1. 1.删除该数中的任意一位数
2. 2. 2.修改该数中的任意一位数
最后需要使得 t a ta ta变成一个完全平方数
问对于每个数我们最少需要操作几步


分析:

因为每个数最多只会有 7 7 7位数,而每位数只会有 12 12 12种操作 ( 0 ∼ 9 、 删 除 、 跳 过 ) (0 \sim 9、删除、跳过) (09)
这样就可以愉快爆搜了dfs打得再好都会T,亲测


代码:

//#pragma GCC optimize(3)
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<queue>
#include<map>
#include<cmath>
#include<vector>
#define LL long long 
using namespace std;
inline LL read() {
    
    
    LL d=0,f=1;char s=getchar();
    while(s<'0'||s>'9'){
    
    if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){
    
    d=d*10+s-'0';s=getchar();}
    return d*f;
}
int ans;
int tf[1000005],bc[1000005];
struct qwq{
    
    
	int n,s;
};
queue<qwq> q;
void bfs(int n)
{
    
    
	q.push((qwq){
    
    n,0});
	int z,y;
	while(q.size())
	{
    
    
		int m=q.front().n,s=q.front().s;
		q.pop();
		if(bc[m]) {
    
    ans=min(ans,s);continue;}
		if(s>7||s>=ans) continue;
		for(int i=10;i<=m*10;i*=10)
		{
    
    
			z=m/i; y=m%(i/10);
			for(int k=0;k<=10;k++)
			{
    
    
				if(k<10) 
				{
    
    
					int num=z*i+k*i/10+y;
					if(tf[num]) continue;
					tf[num]=1;q.push((qwq){
    
    num,s+1});
				}
				else 
				{
    
    
					int num=z*i/10+y;
					if(tf[num]) continue;
					tf[num]=1;q.push((qwq){
    
    num,s+1});
				}
			}
		}
	}
	return;
}
int main()
{
    
    
	int a;double b;
	for(int i=1;i<=1000000;i++) 
	{
    
    
		a=sqrt(i);b=(double)sqrt(i);
		if((double)a==b) bc[i]=1;
	}
	int t=read();
	for(int i=1;i<=t;i++)
	{
    
    
		int n=read();ans=2147483647;
		memset(tf,0,sizeof(tf));tf[n]=1;
		bfs(n);
		printf("%d\n",ans);
	}
	return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35786326/article/details/107939637
今日推荐