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;
}