2056 -- Rectangles (矩形重合)
RectanglesTime Limit: 1000/1000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)Total Submission(s): 5731 Accepted Submission(s): 1802Problem DescriptionGiven 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 .InputInput 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).OutputOutput For each case output the area of their intersected part in a single line.accurate up to 2 decimal places.Sample Input1.00 1.00 3.00 3.00 2.00 2.00 4.00 4.005.00 5.00 13.00 13.00 4.00 4.00 12.50 12.50Sample Output1.0056.25
题意: 给出2个矩形各其中一条对角线,求这2个矩形的重合面积分析:由于不确定输入,所以先分清矩形的左下点和右上点,即对角线都是↗的; 接着分析矩形是否有碰撞假设2个矩形的左下和右上 分别为 (x1,y1),(x2,y2) 和 (x3,y3),(x4,y4)
则且仅当
(x4>x1&&y4>y1&&x3<x2&&y3<y2)即: 矩形B的右上点>矩形A的左下点&&矩形B的左下点<矩形A的右上点成立,2个矩形碰撞现在分析不碰撞的情况把求面积转化为求宽高不难得到 宽(l)=MIN(x2,x4)-MAX(x1,x3); 高(h)=MINy2,y4)-MAX(y1,y3);即得解!
//原始版本: #include <iostream> #include <cmath> using namespace std; struct Lpoint { double x,y; }; int main() { Lpoint num[8]; while(scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&num[0].x,&num[0].y,&num[1].x,&num[1].y,&num[2].x,&num[2].y,&num[3].x,&num[3].y)!=EOF) { double ans=0; num[4].x=num[0].x<num[1].x?num[0].x:num[1].x; //左下 num[4].y=num[0].y<num[1].y?num[0].y:num[1].y; num[5].x=num[0].x>num[1].x?num[0].x:num[1].x; //右上 num[5].y=num[0].y>num[1].y?num[0].y:num[1].y; num[6].x=num[2].x<num[3].x?num[2].x:num[3].x; //左下 num[6].y=num[2].y<num[3].y?num[2].y:num[3].y; num[7].x=num[2].x>num[3].x?num[2].x:num[3].x; //右上 num[7].y=num[2].y>num[3].y?num[2].y:num[3].y; if(!(num[7].x>num[4].x&&num[7].y>num[4].y&&num[6].x<num[5].x&&num[6].y<num[5].y)) //矩形不重合 { printf("0.00/n"); } else { double h,l; h=(num[7].y<num[5].y?num[7].y:num[5].y)-(num[4].y>num[6].y?num[4].y:num[6].y); l=(num[7].x<num[5].x?num[7].x:num[5].x)-(num[4].x>num[6].x?num[4].x:num[6].x); printf("%.2lf/n",h*l); } } }
//代码可读性优化版本: #include <iostream> #include <cmath> #define MAX(a,b) (a)>(b)?(a):(b) #define MIN(a,b) (a)>(b)?(b):(a) using namespace std; struct Lpoint { double x,y; }; int main() { Lpoint num[8]; int i; while(scanf("%lf%lf%lf%lf%lf%lf%lf%lf",&num[0].x,&num[0].y,&num[1].x,&num[1].y,&num[2].x,&num[2].y,&num[3].x,&num[3].y)!=EOF) { for(i=4;i<8;i+=2) { num[i].x=MIN(num[i-4].x,num[i-3].x); //左下 num[i].y=MIN(num[i-4].y,num[i-3].y); num[i+1].x=MAX(num[i-4].x,num[i-3].x); //右上 num[i+1].y=MAX(num[i-4].y,num[i-3].y); } if(!(num[7].x>num[4].x&&num[7].y>num[4].y&&num[6].x<num[5].x&&num[6].y<num[5].y)) //矩形不重合 printf("0.00/n"); else { double h,l,a,b; a=MIN(num[7].y,num[5].y); b=MAX(num[4].y,num[6].y); h=(a-b); a=MIN(num[7].x,num[5].x); b=MAX(num[4].x,num[6].x); l=(a-b); printf("%.2lf/n",h*l); } } }
