码迷,mamicode.com
首页 > 其他好文 > 详细

Rectangle Area

时间:2015-10-25 09:35:51      阅读:230      评论:0      收藏:0      [点我收藏+]

标签:

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.

技术分享

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

  • 得到两个长方形的最大覆盖面积;主要是处理重叠部分
void swapTwo(int *A, int *B)
{
    int tmp = *A;
    *A = *B;
    *B = tmp;
}
void sortFour(int *A, int *C, int *E, int *G)
{
    int tmp = 0;
    if(*A > *C)
        swapTwo(A, C);
    if(*E > *G)
        swapTwo(E, G);
    if(*A > *E)
        swapTwo(A, E);
    if(*C > *E)
        swapTwo(C, E);
    if(*E > *G)
        swapTwo(E, G);
}
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
    int total = (C - A) * (D - B) + (G - E) * (H - F);
    if(A >= G || C <= E || B >= H || D <= F)
        return total;
    else
        {
            sortFour(&A, &C, &E, &G);
            sortFour(&B, &D, &F, &H);
            return total - (E - C) * (F - D);
        }
}
  • 如果存在重叠部分,则把横纵各4个坐标排序,得到中间两个,然后得到重叠部分的面积
int max(int a, int b)
{
    if(a > b)
        return a;
    else 
        return b;
}
int min(int a, int b)
{
    if(a > b)
        return b;
    else
        return a;
}
int computeArea(int A, int B, int C, int D, int E, int F, int G, int H) {
    int total = (C - A) * (D - B) + (G - E) * (H - F);
    if(A >= G || C <= E || B >= H || D <= F)
        return total;
    int top = min(D, H);
    int bottom = max(B, F);
    int left = max(A, E);
    int right = min(C, G);
    return total - (top - bottom) * (right - left);
}
  • 看起来比上面的代码简单,可是速度竟然没有加快;

Rectangle Area

标签:

原文地址:http://www.cnblogs.com/dylqt/p/4908217.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!