2016第七届 蓝桥杯 全国总决赛B题(完全平方数) (练习)

时间:2023-03-09 13:26:38
2016第七届 蓝桥杯 全国总决赛B题(完全平方数) (练习)

道友给看了一道题目,就记录一下吧

题目:

给你0,1,2,3,4,5,6,7,8,9十个数字,要你选出任意一个或几个组合在一起成为完全平方数,每个数字都必须选且只能选一次,求可能的方案。

比如有其中几种符合题意的情况:

0 16 25 73984

0 1 625 73984

0 4 16 537289

0 16 784 5329

0 25 784 1936

思路:先打表,然后再深搜

答案:300

代码:

#include<iostream>
#include<string>
#include<algorithm>
#include<vector>
#include<map>
#include<cstdio>
#include<cstdlib>
#include<cstring>
#include<cstring>
#include<cmath>
using namespace std;
typedef long long ll;
const ll maxn=9876543210;
ll maxnum=sqrt(maxn)+1;
vector<ll> ans;
ll res[100];
bool flag[10];
int sum=0;
bool check(ll x) {
bool judge[10];
memset(judge,false,sizeof(judge));
ll temp=x;
while(temp) {
if(judge[temp%10]==true) return false;
judge[temp%10]=true;
temp/=10;
}
if(x/10*10==x) if(flag[0]==true) return false;
bool exist=false;
temp=x;
while(temp) {
if(flag[temp%10]==true) {
exist=true;
break;
}
temp/=10;
}
if(x/10*10==x) if(flag[0]==true) exist=true;
if(exist) return false;
temp=x;
while(temp) {
flag[temp%10]=true;
temp/=10;
}
if(x/10*10==x) if(flag[0]==false) flag[0]=true;
return true;
}
void renew(ll x) {
if(x/10*10==x) flag[0]=false;
while(x) {
flag[x%10]=false;
x/=10;
}
}
bool checkall() {
bool all=true;
for(int i=0;i<=9;++i) {
if(flag[i]==false) {
all=false;
break;
}
}
return all;
}
void dfs(int index, int pos, int len) {
if(checkall()) {
sum++;
for(int i=0;i<pos-1;++i) printf("%lld ",res[i]);
printf("%lld\n",res[pos-1]);
return;
}
if(index==len) return;
for(int i=index;i<len;++i) {
if(!check(ans[i])) continue;
res[pos]=ans[i];
dfs(i+1,pos+1,len);
renew(ans[i]);
}
}
int main() {
for(ll i=0;i<=maxnum;++i) ans.push_back(i*i);
int len=ans.size();
memset(flag,false,sizeof(flag));
dfs(0,0,len);
printf("%d\n",sum);
return 0;
}

2016第七届 蓝桥杯 全国总决赛B题(完全平方数) (练习)