闲话
第一次被黄题击败一次,特此记录。
解法
首先要明白这是一道 dp 而非贪心。
若是贪心,由于要使答案尽可能地小,我们会使最初选择的蛋糕面积尽可能地大。
但很容易构造反例。例如当 时答案是 而非贪心的 。
故这道题使用的是 dp 算法。令 表示吃掉总面积为 的蛋糕需要的最小蛋糕数。
易得转移方程:。
初始化 后查表即可。
CODE
AC CODE
#include<bits/stdc++.h>
using namespace std;
const int MAXN=1e4+5;
int t,n,dp[MAXN];
int main(){
memset(dp,0x3f,sizeof(dp));
dp[0]=0;
for(int i=1;i<MAXN;i++)
for(int a=1;a*a<=i;a++) dp[i]=min(dp[i],dp[i-a*a]+1);
scanf("%d",&t);
for(int Case=1;Case<=t;Case++){
scanf("%d",&n);
printf("Case #%d: %d\n",Case,dp[n]);
}
return 0;
}