16蓝桥杯决赛 凑平方数

用全排列直接搜索,可行的结果放到set里面判重,注意一下用long long就行了。

#include<iostream>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<cstring>
#include<set>
#include<cstdlib>
using namespace std;
typedef long long ll;
int Count=0; 
int ans[10]={0,1,2,3,4,5,6,7,8,9};
ll node[11]={0};
set<string> s;//判重 
int judge(ll x)
{
	long long m=floor(sqrt(x)+0.5);
	if(m*m==x)return 1;
	return 0;
}
void dfs(int x,int y,ll prd)//结点位置 
{
	if(y==10){
		if(judge(prd)){
			node[y]=prd;
			/*for(int i=0;i<10;i++)
			{
				if(node[i]!=-1)printf(" ");
				printf("%d",ans[i]);
			} 
			printf(",");
			for(int i=0;i<=10;i++)
				printf("%lld ",node[i]);
			*/
			ll node1[10];
			int tot=0;
			for(int i=0;i<=10;i++){
				if(node[i]!=-1)
				{
					node1[tot++]=node[i];
				}
			}
			sort(node1,node1+tot);
			/*for(int i=0;i<tot;i++)
			{
				printf("%lld ",node1[i]);
				
			}
			printf("\n");*/
			char str[20]="";
			for(int i=0;i<tot;i++){
				char buf[30]="";
				sprintf(buf,"%lld ",node1[i]);
				strcat(str,buf);
			}
			
			//printf(",%s\n",str);
			
			string str1(str);
			s.insert(str1);
			node[y]=-1;
		}
		return;
	}
	if(judge(prd))//设置结点 
	{
		node[y]=prd;
		dfs(y,y+1,ans[y]);
		node[y]=-1;
	}
	if(prd!=0)//不设置 
		dfs(x,y+1,prd*10+ans[y]);
}
int main()//最大平方数1090011976 
{
	
	memset(node,-1,sizeof(node));
	do{
		dfs(0,1,ans[0]);
	}while(next_permutation(ans,ans+10));
	for(set<string>::iterator it=s.begin();it!=s.end();it++)
		cout<<*it<<endl;
	printf("%d",s.size());
	return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值