杭电 2056

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2056

Rectangles

Problem Description

Given two rectangles and the coordinates of two points on the diagonals of each rectangle,you have to  calculate the area of the intersected part of two rectangles. its sides are parallel to OX and OY .


Input

Input The first line of input is 8 positive numbers which indicate the coordinates of four points that must be on each diagonal.The 8 numbers are x1,y1,x2,y2,x3,y3,x4,y4.That means the two points on the first rectangle are(x1,y1),(x2,y2);the other two points on the second rectangle are (x3,y3),(x4,y4).


Output

Output For each case output the area of their intersected part in a single line.accurate up to 2 decimal places.


Sample Input

1.00 1.00 3.00 3.00 2.00 2.00 4.00 4.00

5.00 5.00 13.00 13.00 4.00 4.00 12.50 12.50


Sample Output

1.00

56.25、

翻译如下:

矩形 

问题描述 

给定两个矩形和每个矩形对角线上两点的坐标,必须计算两个矩形相交部分的面积。它的侧面与Ox和Oy平行。

 输入 

输入第一行输入的是8个正数,表示必须在每个对角线上的四个点的坐标。8个数字是x1、y1、x2、y2、x3、y3、x4、y4。这意味着第一个矩形上的两个点是(x1、y1)、(x2、y2);第二个矩形上的其他两个点是(x3、y3)、(x4、y4)。

 产量 

每种情况下的输出在一行中输出其相交部分的面积。精确到小数点后2位。 

样本输入 

1.00 1.00 3.00 3.00 2.00 2.00 4.00 4.00

 5.00 5.00 13.00 13.00 4.00 4.00 12.50 12.50

 样品输出 

1.00

56.25

解题思路:

这道题求矩形的公共面积可以分成2个问题

1.是否有公共的面积?

2.如果有公共面积,那么,是多少??

先解决第一个问题。我们考虑数轴上的有2个线段,显然,如果2个线段要有相交的部分,那么这个相交的部分一定是2个线段左端点的较大值和右端点的较小值所构成的。

也就是说,【2个左端点的较大值和2个右端点的较小值】之间的部分就是我们需要的公共区间。

同时可以推出,如果左端点的较大值如果本身就比右端点的较小值要大,这2个线段绝对没有公共区间。

这个结论放在2维的坐标系中,很显然可以推出只要X坐标和Y坐标同时都满足上面这个条件!那么就一定会有公共区间。

另外需要注意的是,2个矩形相交,不意味着有一个顶点在另外一个矩形内。有反例。

那么我们只要根据

X轴上的2个左端点的较大值和2个右端点的较小值

y轴上的2个下端点的较大值和2个上端点的较小值

就能得出答案。

当然,如果这道题是100%有相交的前提的话,也可以对横纵坐标分别排序,取中间的2个值作差就可以计算答案,画个图就明白了。

这道题输入的2个对角点顺序他完全是随机的

代码如下:

#include

#include

#include

#include

#include

#include

using namespace std;

double x[10],y[10],ans,lx,rx,ly,ry;

int i;

void change(double &xx,double &yy){

double t;

t=xx; xx=yy; yy=t;

}

int main(){

    while(scanf("%lf%lf",&x[1],&y[1])!=EOF){

      for(i=2;i<=4;i++){

        scanf("%lf%lf",&x[i],&y[i]);

      }

      if(x[1]>x[2]){change(x[1],x[2]);}

      if(x[3]>x[4]){change(x[4],x[3]);}

      if(y[1]>y[2]){change(y[1],y[2]);}

      if(y[3]>y[4]){change(y[4],y[3]);}  //处理读入的数据。

      lx=max(x[1],x[3]); rx=min(x[2],x[4]); //计算X轴上的左端的较大值,右端的较小值

      ly=max(y[1],y[3]); ry=min(y[2],y[4]); //计算y轴上的下端的较大值,上端的较小值

      if(lx<=rx&&ly<=ry){                  //公共矩形的左端不能超过右端,下端不能超上端

        ans=1.0*fabs(rx-lx)*fabs(ry-ly);  //计算答案

        printf("%.2lf\n",ans);

      }

      else{printf("0.00\n"); continue;} //没有公共区间,输出0.00

    }

    return 0;

}

你可能感兴趣的:(杭电 2056)