USACO Training:Packing Rectangles (IOI95) Accepted

来源:互联网 发布:手机erp工业软件 编辑:程序博客网 时间:2024/05/22 19:09

Packing Rectangles
IOI 95
 
The six basic layouts of four rectangles
Four rectangles are given. Find the smallest enclosing (new) rectangle into which these four may be fitted without overlapping. By smallest rectangle, we mean the one with the smallest area.

All four rectangles should have their sides parallel to the corresponding sides of the enclosing rectangle. Figure 1 shows six ways to fit four rectangles together. These six are the only possible basic layouts, since any other layout can be obtained from a basic layout by rotation or reflection. Rectangles may be rotated 90 degrees during packing.

There may exist several different enclosing rectangles fulfilling the requirements, all with the same area. You must produce all such enclosing rectangles.

PROGRAM NAME: packrec
INPUT FORMAT
Four lines, each containing two positive space-separated integers that represent the lengths of a rectangle's two sides. Each side of a rectangle is at least 1 and at most 50.

SAMPLE INPUT (file packrec.in)
1 2
2 3
3 4
4 5

OUTPUT FORMAT
The output file contains one line more than the number of solutions. The first line contains a single integer: the minimum area of the enclosing rectangles. Each of the following lines contains one solution described by two numbers p and q with p<=q. These lines must be sorted in ascending order of p, and must all be different.
SAMPLE OUTPUT (file packrec.out)
40
4 10
5 8

这道题很繁,难点在于考虑到所有情况。

按照题意4个矩形有6种基本排列方式(如图):

 

设框住它们的最小矩形的矩形水平边长为tx,竖直边长为ty,把4矩形水平边长存入C数组rx[4],竖直边长存入数组ry[4]。

对于前5种排列方式:

        第一种
        tx=rx[0]+rx[1]+rx[2]+rx[3];
        ty=max(ry[0],ry[1],ry[2],ry[3]);
       第二种:
        tx=max(rx[0],rx[1]+rx[2]+rx[3]);
        ty=max(ry[1],ry[2],ry[3])+ry[0];
       第三种
        tx=max(rx[0]+rx[1],rx[1]+rx[2]+rx[3]);
        ty=max(ry[1],ry[0]+ry[2],ry[0]+ry[3]);

       第四和第五种写出来一样:
        tx=max(rx[0]+rx[1]+rx[2],rx[0]+rx[1]+rx[3]);
        ty=max(ry[0],ry[1],ry[2]+ry[3]);

对于最后一种方式,它的高很简单:

ty=max(ry[3]+ry[0],ry[2]+ry[1]);

麻烦的是它的宽,需要分成如图所示的5种情况:

        if(ry[2]==ry[3]) //第6.1种
                tx=max(rx[1]+rx[0],rx[2]+rx[3]);
        else if(ry[2]>=ry[0]+ry[3]){ //第6.2种
                tx=max(rx[1],rx[0]+rx[2]);
                tx=max(tx,rx[2]+rx[3]);
        }else if(ry[3]>=ry[1]+ry[2]){ //第6.3种
                tx=max(rx[0],rx[1]+rx[3]);
                tx=max(tx,rx[2]+rx[3]);
        }else if(ry[2]>ry[3] && ry[2]<ry[0]+ry[3]){//第6.4种
                tx=max(rx[2]+rx[0],rx[2]+rx[3]);
                tx=max(tx,rx[0]+rx[1]);
        }else{//第6.5种
                tx=max(rx[3]+rx[1],rx[3]+rx[2]);
                tx=max(tx,rx[0]+rx[1]);
        }

每次计算出tx和ty就用它们围成的矩形面积和当前的最小值比较,如果相等就记下来,如果更小就更新最小值。

枚举出所有矩形的组合,按要求输出就可以了。

原创粉丝点击