hdu_2056(Rectangles)

题目不多解释,就是计算两个长方形的交集面积

http://acm.hdu.edu.cn/showproblem.php?pid=2056

      我的方法不是最简单的,但是我觉得是很易懂得,可读性很高。个人觉得代码简洁是一方面,但是可读性也一点不亚于简洁和高效。对于新手,或者做acm的人可能会忽视这点,觉得代码少,速度快,正确过关就ok了,毕竟这些代码一旦 ac 就几百年都不会去看了。但是等到,学习过应用软件的设计之后,代码的可读性的重要就显而易见,因为经常需要修改,需要和别人合作,如果都是参数都是x1、x2 ... 函数都是fun1()  fun2() 别说别人的看不懂,自己的都看到头大。(补充: 我并不是高手、也没有一线开发经验,还是个大一学生,但有些东西,不用太多经验就能够想清楚,现在就要开始养成良好习惯)

     写acm不一定就是为了进集训队,可以用来提高编程水平,保持感觉,培养良好的编程习惯;

    

  废话说多了,进入正题。

  此题不难,相信大家都知道,但是就是一个烦,分析的情况较多,容易遗漏,出错,而且出错后难以查找。所以我使用c++的类,来封装Rectangle;如下:

class Rectangle
{
private:
    double x_1, x_2, y_1, y_2;
    double center_x, center_y;
    double width, height;
public:
    Rectangle(double x1, double y1, double x2, double y2);
    friend Rectangle findTheRectangle(Rectangle& , Rectangle&);   //找到可能存在的长方形,如果存在相交的部分,它也是一个长方形,而且一定是x1, x2, x3, x4和
//y1, y2, y3, y4中除去最大、最小点后,剩下的4个点组成。 friend
double calculateTheAer(Rectangle&, Rectangle&, Rectangle&); //计算面积,前两个参数是原始的长方形,最后一个参数是上一步计算出来的长方形。通过原
                                           //始长方形的中点距离和长宽比较,判断交集是否存在,存在就返回第三个参数的面积,不存
                                           //在就返回 0 。 };

有了这个类 题目分析就一目了然了,如果做出来出错,通过试调也就马上可以查出错误,是不是复杂的分析马上就简单了?
完整代码如下:

#include <iostream>
#include <cmath>

using namespace std;

class Rectangle
{
private:
    double x_1, x_2, y_1, y_2;
    double center_x, center_y;
    double width, height;
public:
    Rectangle(double x1, double y1, double x2, double y2);
    friend Rectangle findTheRectangle(Rectangle& , Rectangle&);    
    friend double calculateTheAer(Rectangle&, Rectangle&, Rectangle&);
};

Rectangle::Rectangle(double x1, double y1, double x2, double y2)
{
    x_1 = x1 > x2 ? x2 : x1;          //构造函数中保证  x_1 < x_2, y_1 < y_2;方便之后的计算
    x_2 = x1 > x2 ? x1 : x2;

    y_1 = y1 > y2 ? y2 : y1;
    y_2 = y1 > y2 ? y1 : y2;

    center_x = (x1 + x2) / 2;
    center_y = (y1 + y2) / 2;

    width = x_2 - x_1;
    height = y_2 - y_1;
}

Rectangle findTheRectangle (Rectangle& r1, Rectangle& r2)
{
    double x1, x2, y1, y2;
    
    x1 = r1.x_1 > r2.x_1 ? r1.x_1 : r2.x_1;
    x2 = r1.x_2 > r2.x_2 ? r2.x_2 : r1.x_2;

    y1 = r1.y_1 > r2.y_1 ? r1.y_1 : r2.y_1;
    y2 = r1.y_2 > r2.y_2 ? r2.y_2 : r1.y_2;

    return Rectangle(x1, y1, x2, y2);
}

double calculateTheAer(Rectangle& r1, Rectangle& r2, Rectangle& r3)
{
    if (fabs(r1.center_x - r2.center_x) < (r1.width + r2.width) / 2 && fabs(r1.center_y - r2.center_y) < (r1.height + r2.height) / 2)
    {
        return r3.width * r3.height;
    }
    else 
        return 0.0;
}

int main ()
{
    double x1, x2, x3, x4, y1, y2, y3, y4;
    while (cin >> x1 >> y1 >> x2 >> y2 >> x3 >> y3 >> x4 >> y4)
    {
        Rectangle r1(x1, y1, x2, y2);
        Rectangle r2(x3, y3, x4, y4);

        Rectangle r3 = findTheRectangle(r1, r2);

        printf("%.2lf\n" ,calculateTheAer(r1, r2, r3));
    }

    return 0;
}

 

 

posted @ 2012-07-30 12:26  MonkeyDLky  阅读(1727)  评论(0编辑  收藏  举报