1.OJ 2056(http://acm.hdu.edu.cn/showproblem.php?pid=2056)
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
2.思路:一开始做的时候只是按照题目给的数据画了一下图然后列出式子,后来发现其实没有这么简单,相交的情况有4种,而除了相交以外,还有包含于相离,要想解决这道题得做一定的处理从而把复杂问题简单化(一开始打算暴力求解,把所有情况都列出来,后来发现实在是吃力不讨好)。
所以正确打开方式是先分别使x1与x2、y1与y2、x3与x4、y3与y4大小规范,前面的恒小于后面的(1一定比2小,3一定比4小)如x1<x2,使两个点永远是矩形的左下点和右上点。符合条件则不处理,不符合条件则两两交换。然后记录两个矩形的右上点较小的点和左下点较大的点,可以得出2个坐标点,即为重叠矩形的对角点,再把两个点的横坐标相减、纵坐标相减的值相乘就得出了重叠矩形的长和宽。
ps:左下点为(x1,y1),(x3,y3)。右下点为:(x2,y2),(x4,y4)。
所以相交或者包含时:
a=(x1,x3较大的一方)
b=(y1,y3较大的一方)
c=(x2,x4较小的一方)
d=(y2,y4较小的一方)
左下点(a,c).....右上点(b,d)
重叠的面积=(b-a)*(d-c)
相离(a>b或者c>d):直接令面积为0.00。
3.源代码:
#include<stdio.h>
int change(double* a,double* b){//交换函数
double t;
if((*a)>(*b)){
t = (*a);
(*a) = (*b);
(*b) = t;
}
}
double max(double a,double b){//取最大值
if(a>b)
return a;
else
return b;
}
double min(double a,double b){//取最小值
if(a<b)
return a;
else
return b;
}
int main(){
double x1,y1,x2,y2,x3,y3,x4,y4,s; while(scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&x1,&y1,&x2,&y2,&x3,&y3,&x4,&y4)!=EOF){
change(&x1,&x2);
change(&y1,&y2);
change(&x3,&x4);
change(&y3,&y4);
a=max(x1,x3);
b=max(y1,y3);
c=min(x2,x4);
d=min(y2,y4);
if(a>b || c>d){//相离
s=0;
}
else s=(x2-x1)*(y2-y1);//相交或者包含
printf("%.2lf\n",s);
}
}