(数论方法)参见:本博客URAL 1593。
题目大意:给出正整数n,求其最少可以表示为几个数的平方之和。
Time Limit:1000MS Memory Limit:65536KB 64bit IO Format:%I64d & %I64u
数据规模:n<=60000。
理论基础:无。
题目分析:先预处理出小于60000的平方数。存储在p[i]中,p[i]=i*i。dp[p[i]]=1,其余dp[i]=i,p[i]=i(i个1相加)。
dp[i]表示n==i时至少可以表示为几个数的平方之和。
其次,我们可以得出状态转移方程:dp[i]=min(dp[i-p[j]]+dp[p[j]],dp[i](j<=i&&p[j]<=i))。
最后的答案即为dp[n]。
代码如下:
#include<iostream>
#include<cstring>
#include<string>
#include<cstdlib>
#include<cstdio>
#include<cmath>
#include<algorithm>
#include<queue>
#include<ctime>
#include<vector>
using namespace std;
typedef double db;
#define DBG 1
#define maa (1<<31)
#define mii ((1<<31)-1)
#define ast(b) if(DBG && !(b)) { printf("%d!!|\n", __LINE__); while(1) getchar(); } //调试
#define dout DBG && cout << __LINE__ << ">>| "
#define pr(x) #x"=" << (x) << " | "
#define mk(x) DBG && cout << __LINE__ << "**| "#x << endl
#define pra(arr, a, b) if(DBG) {\
dout<<#arr"[] |" <<endl; \
for(int i=a,i_b=b;i<=i_b;i++) cout<<"["<<i<<"]="<<arr[i]<<" |"<<((i-(a)+1)%8?" ":"\n"); \
if((b-a+1)%8) puts("");\
}
template<class T> inline bool updateMin(T& a, T b) { return a>b? a=b, true: false; }
template<class T> inline bool updateMax(T& a, T b) { return a<b? a=b, true: false; }
typedef long long LL;
typedef long unsigned int LU;
typedef long long unsigned int LLU;
#define N 60000
int dp[N+1],p[N+1],n;
void init()
{
memset(dp,0,sizeof dp);
memset(p,0,sizeof p);
for(int i=1;i*i<=60000;i++)
{
p[i]=i*i;
dp[p[i]]=1;
}
for(int i=0;i<=60000;i++)
{
if(!dp[i])dp[i]=i;
}
}
void solve(int n)
{
for(int i=1;i<=(int)sqrt((double)n);i++)
{
for(int j=p[i];j<=n;j++)
{
if(dp[j]>dp[j-p[i]]+dp[p[i]])
dp[j]=dp[j-p[i]]+dp[p[i]];
}
}
printf("%d\n",dp[n]);
}
int main()
{
init();
while(~scanf("%d",&n))
{
solve(n);
}
return 0;
}
其中,dp方法为分段dp,即每两个平方数之间的数为一段,这样避免了许多关于p[j]与i的大小判断。
by:Jsun_moon http://blog.youkuaiyun.com/jsun_moon