查看: 2792| 回复: 1
跳转到指定楼层
上一主题 下一主题
收起左侧

Microsoft : Find the largest square fits a rectangle

全局:

注册一亩三分地论坛,查看更多干货!

您需要 登录 才可以下载或查看附件。没有帐号?注册账号

x
Given a rectangle with known width and height, design an algorithms to fill
the rectangle using n squares(n is integer, also given) and make sure in the
result the wasting area is minimized. Length of square doesn't have to be integer.

I.e, given width=3,height=2,n=5, one solution is that rectangle can
be filled with five 1x1 squares and the wasting area is 1. Another
solution could be filled with five 0.9x0.9 squares, but the wasting area is more than first solution.

上一篇:找最大子矩阵 (哪家的我忘了)
下一篇:Hanoi problem
🔗
 楼主| wwwyhx 2011-7-6 00:47:19 | 只看该作者
全局:
说说我的思路:

可以证明最优解的情况一定是方格可以填满行的,或是方格可以填满列的(填满了再往上排)。
可以分行列来考虑。
如果是行,行的长度为l.,考虑方格长度为l/n,l/(n-1)...l的情况,找最优值(二分优化)
在分列来考虑,记录最优值。

我的代码:

  1. bool fits(float l, float w, int m, int n)
  2. {
  3.         assert(l>0 && w>=0 && m>0 && n>0);

  4.         if (n <= m && w >= l/m)
  5.                 return true;

  6.         if (w < l/m) return false;

  7.         return fits(l, w-l/m, m, n-m);
  8. }

  9. float CalcLen(int l, int w, int n)
  10. {
  11.         assert(l>0 && w>0 && n>0);

  12.         int nLow = 1;
  13.         int nHigh = n;
  14.         int nBest = -1;

  15.         while (nLow < nHigh)
  16.         {
  17.                 int nMid = (nLow + nHigh)/2;
  18.                 if (fits(l, w, nMid, n))
  19.                 {
  20.                         nHigh = nMid-1;
  21.                         nBest = nMid;
  22.                 }
  23.                 else
  24.                         nLow = nMid+1;
  25.         }

  26.         if (nLow == nHigh && fits(l, w, nLow, n))
  27.                 nBest = nLow;

  28.         return (float)l/(float)nBest;
  29. }

  30. float GetLargest(int l, int w, int n)
  31. {
  32.         assert(l>0 && w>0 && n>0);

  33.         float r1 = CalcLen(l, w, n);
  34.         float r2 = CalcLen(w, l, n);

  35.         return r1>r2?r1:r2;
  36. }
复制代码
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 注册账号
隐私提醒:
  • ☑ 禁止发布广告,拉群,贴个人联系方式:找人请去🔗同学同事飞友,拉群请去🔗拉群结伴,广告请去🔗跳蚤市场,和 🔗租房广告|找室友
  • ☑ 论坛内容在发帖 30 分钟内可以编辑,过后则不能删帖。为防止被骚扰甚至人肉,不要公开留微信等联系方式,如有需求请以论坛私信方式发送。
  • ☑ 干货版块可免费使用 🔗超级匿名:面经(美国面经、中国面经、数科面经、PM面经),抖包袱(美国、中国)和录取汇报、定位选校版
  • ☑ 查阅全站 🔗各种匿名方法

本版积分规则

>
快速回复 返回顶部 返回列表