P11246 小杨和整数拆分 题解
P11246 小杨和整数拆分 题解
题意简述
小杨有一个正整数
请你计算总和为
开始解题!
这是一道很经典的广搜变式题,我们令当前状态为
最后是时间复杂度,大家可能觉得这样的做法时间复杂度比较玄学,实则不然,我们由拉格朗日四平方和定理可得,一定会有 总之能过
code :
#include <bits/stdc++.h>
using namespace std;
int n;
struct node {
int s, f;
};
queue<node> q;
int bfs(int n) {
q.push({0,0});
while(!q.empty()) {
node now = q.front();
q.pop();
int ss = now.s;
int no = now.f;
for(int i = 1; i * i <= n; i++) {
ss = now.s + i * i;
if(ss == n) return no + 1;
if(ss > n) break;
q.push((node){ss, no + 1});
}
}
return -1;
}
int main() {
cin >> n;
cout << bfs(n) << endl;
}
AC record
其实从记录来看,这个代码的复杂度还是很优秀的。
做完了。