95-Rectangle Area

来源:互联网 发布:数据库的概念结构设计 编辑:程序博客网 时间:2024/05/21 11:31

-223. Rectangle Area My Submissions QuestionEditorial Solution
Total Accepted: 37901 Total Submissions: 126073 Difficulty: Easy
Find the total area covered by two rectilinear rectangles in a 2D plane.

Each rectangle is defined by its bottom left corner and top right corner as shown in the figure.

Rectangle Area
Assume that the total area is never beyond the maximum possible value of int.

求两个矩形并集的总面积

思路:求出交集
利用容斥原理

|AB|=|A|+|B||AB|

考虑特殊用例:
比如矩形收缩为点
矩形收缩为线
矩形面积越界
整型求和越界
无交集
有交集

class Solution {public:    int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {        long long resAx,resBy,resCx,resDy;        long long area1,area2,intersect=-1;        resAx= max(A,E);        resCx= min(C,G);        resBy=max(B,F);        resDy=min(D,H);//求出交集矩形对角点        if(resCx-resAx<=0||resDy-resBy<=0)intersect=0; //交集为空        else intersect = abs(resCx-resAx)*abs(resDy-resBy);        if((A==C||B==D)||(E==G)||F==H)intersect=0;//修补收缩为线的情况        area1=(C-A)*(D-B),area2 = (G-E)*(H-F);        return area1+area2-intersect;    }};
0 0