题解:P2232 [HNOI2002] 填数游戏
写在前面
我的文章真的是自己写的,不是 AI 生成的,求管理员通过,不要以 AI 生成为理由打回,谢谢!
基础思路
先构造两个数列,一个长度为
例:n = 3, m = 5
构造数列一:1 16 64
构造数列二:9 16 25 49 225
计算答案:
| 9 | 16 | 25 | 49 | 225 | |
|---|---|---|---|---|---|
| 1 | 9 | 16 | 25 | 49 | 225 |
| 16 | 144 | 256 | 400 | 784 | 3600 |
| 64 | 576 | 1024 | 1600 | 3136 | 14400 |
正确性证明:如果一个数列中每一个数都是完全平方数,各数之和也是完全平方数,那么给这个数列的每一项都乘以一个完全平方数,得到的新数列显然也具有该性质。
实现细节
构造数列的生成
人工构造方法可能会使得最终答案突破
为了使搜索不会无限进行,给定上界
去重
为了保证各个数字不同,如果答案矩阵中出现了重复值,那么需要换一个初始值重新搜索构造数列。
代码
#include<stdio.h>
#include<vector>
#include<unordered_set>
int n,m;
long long sqrt(long long i){
long long ans=0,step=1;
while(step){
long long res=ans+step;
if(res*res<=i){
ans=res;
step<<=1;
}
else step>>=1;
}
return ans;
}
std::vector<long long>path;
const int lim=125;
bool dfs(long long num,long long sum,short tot){
if(num==lim)return false;
if(!tot){
long long res=sqrt(sum);
return res*res==sum;
}
path.push_back(num*num);
if(dfs(num+1,sum+path.back(),tot-1))return true;
path.pop_back();
return dfs(num+1,sum,tot);
}
std::vector<std::vector<long long>>ans1,ans2;
long long ans[15][15];
std::unordered_set<long long>s;
int main(){
scanf("%d%d",&n,&m);
while(true){
dfs(ans1.size(),0,n);
for(const auto&v:ans2){
bool flag=false;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
ans[i][j]=path[i]*v[j];
if(s.count(ans[i][j])){
flag=true;
s.clear();
break;
}
s.insert(ans[i][j]);
}
if(flag)break;
}
if(flag)continue;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
printf("%lld ",ans[i][j]);
}
putchar('\n');
}
return 0;
}
ans1.push_back(path);
path.clear();
dfs(ans2.size(),0,m);
for(const auto&v:ans1){
bool flag=false;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
ans[i][j]=v[i]*path[j];
if(s.count(ans[i][j])){
flag=true;
s.clear();
break;
}
s.insert(ans[i][j]);
}
if(flag)break;
}
if(flag)continue;
for(int i=0;i<n;i++){
for(int j=0;j<m;j++){
printf("%lld ",ans[i][j]);
}
putchar('\n');
}
return 0;
}
ans2.push_back(path);
path.clear();
}
}