积木城堡题解
据说这道题是原来浙江省选的题目(╯‵□′)╯︵┻━┻ ,你特么确定不是在逗我!!!
这其实是一道简单的背包问题.时间有点儿紧,200ms可过
(跪求大神给出50ms以下算法!神犇Orz!!)
每座城堡的高度拿来动规求出拿走积木后可能的高度,再从上往下枚举可能相同的高度,找到就输出.
丑陋的代码
#include "cstdio" int n,g[101][101],h[101],i,j,k,hs[101]; int ht; bool f[101][10001],flag; void read(){ scanf("%d",&n); for(i=1;i<=n;++i){ j=1; while(scanf("%d",&k),k!=-1){ h[i]+=(g[i][j]=k); ++j; } f[i][0]=true; hs[i]=--j; } } int main(int argc, char const *argv[]) { read(); for(i=1;i<=n;++i){ for(j=1;j<=hs[i];++j){ for(k=h[i];k>-1;--k){ f[i][k]=f[i][k]||f[i][k-g[i][j]]; //if this height is reachable after removing some of the blocks } } } ht=20000;//of course, a number that is much bigger than the max height has been treated as INF for(i=1;i<=n;++i){ if(h[i]<ht){ ht=h[i];//decrease ht to the min-height of the castels } } flag=true;//is not finished flag while(ht>0&flag){ for(i=1;i<=n;++i){ if(!f[i][ht]){//this test did not passed while(--ht,!f[i][ht]&&ht>0);//decrease ht to the nearest reachable height after removing blocks break; }else{ if(i==n){//all tests are done flag=false;//finished } } } } printf("%d", ht);//output max return 0; }
似乎很短?
好丑,一定要去掉注释和其他多余代码.
#include "cstdio" int n,g[101][101],h[101],i,j,k,hs[101]; int ht; bool f[101][10001],flag; void read(){ scanf("%d",&n); for(i=1;i<=n;++i){ j=1; while(scanf("%d",&k),k!=-1){ h[i]+=(g[i][j]=k); ++j; } f[i][0]=true; hs[i]=--j; } } int main(){ read(); for(i=1;i<=n;++i) for(j=1;j<=hs[i];++j) for(k=h[i];k>-1;--k) f[i][k]=f[i][k]||f[i][k-g[i][j]]; ht=20000; for(i=1;i<=n;++i) if(h[i]<ht) ht=h[i]; flag=true; while(ht>0&flag) for(i=1;i<=n;++i) if(!f[i][ht]){ while(--ht,!f[i][ht]&&ht>0); break; }else if(i==n) flag=false; printf("%d", ht); return 0; }