7.2 凑平方数

题目:

凑平方数 
把0~9这10个数字,分成多个组,每个组恰好是一个平方数,这是能够 
办到的。

比如:0, 36, 5948721

再比如: 
1098524736 
1, 25, 6390784 
0, 4, 289, 15376 
等等…

注意,0可以作为独立的数字,但不能作为多位数字的开始。 
分组时,必须用完所有的数字,不能重复,不能遗漏。

如果不计较小组内数据的先后顺序,请问有多少种不同的分组方案?

思路: 
先用全排列列举出所有序列,然后对每一个序列使用dfs搜索平方数组并转成有序字符串,使用set容器存储达到去重目的,最后set的大小即答案。
 

 

#include<bits/stdc++.h>
#define MAX 150005
#define MOD 1000000007
typedef long long LL;
//const int INF = 1e9+7;
#define VM 1000010
using namespace std;
#define inf 0.00000001

//char str[1005],ans[1005];
int p;
int has[1005],op[1005];
struct node{
    char c;
    int num;
    bool operator < (const node &a)const
    {
        if(num!=a.num)
            return num < a.num;
        return c>a.c;
    }
}nd[1005];
template<typename T> string toString(const T& t){
    ostringstream oss;  //创建一个格式化输出流
    oss<<t;             //把值传递如流中
    return oss.str();
}
set<string> ans;//
int shu[10]={0,1,2,3,4,5,6,7,8,9};
LL divs[10];
bool pfs(LL num){
    return (LL)sqrt(num)*(LL)sqrt(num)==num;
}
void dfs(int cur,int n){//当前搜索到第i位,当前记录了n个平方数
    if(cur==10){
        LL tmp[10];
        for(int i=0;i<n;i++){
            tmp[i]=divs[i];
        }
        //copy(div,div+n,tmp);
        sort(tmp,tmp+n);//n个平方数排序后放在set,防止不同全排列带来的重复
        string s;
        for(int i=0;i<n;i++)
            //string c=;
            s+=toString(tmp[i])+',';
            //to_string()
        ans.insert(s);
        return ;
    }
    if(shu[cur]==0){//0的处理
        divs[n]=0; //划分的第n个数为0
        dfs(cur+1,n+1);
        return ;
    }
    LL num=0;
    for(int i=cur;i<10;i++){
        num=num*10+shu[i];
        if(pfs(num)){
            divs[n]=num;
            dfs(i+1,n+1);
        }
    }
}
int main()
{
    do{
        dfs(0,0);
    }while(next_permutation(shu,shu+10));
    cout<<ans.size()<<endl;
	return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值