1. 程式人生 > >hdu2056 Rectangles(矩形重疊)

hdu2056 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

原題連結如下:

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

設以線段P1P2作為矩形R的對角線,以Q1Q2為矩形T的對角線,若矩形R和T不相交,則線段不會相交。

設P1 = (x1,y1), P2 = (x2, y2), Q1 = (x3, y3), Q2 = (x4, y4);

將矩形R的x座標的最小邊界用minRX = (x1, x2)表示,以此類推。

若兩矩形相交,設為矩形F。則矩形F的x座標的最小邊界minFX = max(minRX, minTX), minFY = max(minRY, minTY),

maxFX = min(maxRX, maxTX), maxFY = min(maxFY, maxTY).

得到F的各個值後,只要判斷矩形F是否成立就可以判斷是否相交了, 若minFX > maxFX, 或minFY > maxFY則矩形不相交,否則相交。

AC程式碼如下:

#include<iostream>
#include<cstdio>
#include<algorithm>
using namespace std;
double _max(double x, double y)
{
    if(x > y)
        return x;
    else
        return y;
}
double _min(double x, double y)
{
    if(x < y)
        return x;
    else
        return y;
}
int main()
{
    double x1, y1, x2, y2, x3, y3, x4, y4, area;
    while(scanf("%lf%lf%lf%lf%lf%lf%lf%lf", &x1, &y1, &x2, &y2, &x3, &y3, &x4, &y4) != EOF)
    {
        double minRX = min(x1, x2), minRY = min(y1, y2), maxRX = max(x1, x2), maxRY = max(y1, y2);
        double minTX = min(x3, x4), minTY = min(y3, y4), maxTX = max(x3, x4), maxTY = max(y3, y4);
        x1 = _max(minRX, minTX), x2 = _min(maxRX, maxTX);
        y1 = _max(minRY, minTY), y2 = _min(maxRY, maxTY);
        if(x1 > x2 || y1 > y2)
            area = 0.0;
        else
        {
            double a = x2 - x1, b = y2 - y1;
            area = a*b;
        }
        printf("%.2f\n", area);
    }

    return 0;
}