用全排列直接搜索,可行的结果放到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;
}