HDU 1542

题目描述:

There are several ancient Greek texts that contain descriptions of the fabled island Atlantis. Some of these texts even include maps of parts of the island. But unfortunately, these maps describe different regions of Atlantis. Your friend Bill has to know the total area for which maps exist. You (unwisely) volunteered to write a program that calculates this quantity. 

输入一个n,表示矩形个数然后左下角和右上角坐标,x1,y1,x2,y2,当n=0时输入结束;

样例;

input:

2
10 10 20 20
15 15 25 25.5
0
output:

Test case #1
Total explored area: 180.00 
第一次做扫描线,看了很多博客,也是在模仿别人的代码在写,感觉理解还不够深刻,将所有的横纵坐标从小到大排序进行完之后,我们只能选择脑补一根线从左向右扫过去,一开始我们用一个flag来记录这条边是矩形左边的边或者右边的边(1或-1),现在在树中用一个cover变量来记录现在插入边的情况,如果cover>0那说明已经插入过一条左边的边,那么这在图中表现出来其实就是两个矩形有交叉的部分,那么此时我们将这交叉部分的面积算出来,并更新该点x的坐标表示在这个x之前的面积已经计算过。就这一样一条一条边的插入最后得出结果,具体的还是看代码自行脑补吧,这个确实很抽象。
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
const int MAXM=110;
struct line
{
    double x;
    double y1,y2;
    int flag;
    double operator <(line l2)
    {
        return x=r)
        return 0;
    if (tree[num].flag)
    {
        if (tree[num].cover>0)
        {
            double tmp=tree[num].x;
            double square=(x-tmp)*(tree[num].y2-tree[num].y1);
            tree[num].x=x;
            tree[num].cover+=flag;
            return square;
        }
        else
        {
            tree[num].cover+=flag;
            tree[num].x=x;
            return 0;
        }
    }
    double square1,square2;
    square1=insert(num*2,x,l,r,flag);
    square2=insert(num*2+1,x,l,r,flag);
    return square1+square2;

}
int main()
{
    int cnt=1;
    while(scanf("%d",&n)!=EOF)
    {
        if (n==0) break;
        int index=1;
        for (int i=1;i<=n;i++)
        {
            double x1,y_down,x2,y_up;
            scanf("%lf%lf%lf%lf",&x1,&y_down,&x2,&y_up);
            l[index].x=x1;
            l[index].y1=y_down;
            l[index].y2=y_up;
            l[index].flag=1;
            y[index]=y_down;
            index++;
            l[index].x=x2;
            l[index].y1=y_down;
            l[index].y2=y_up;
            l[index].flag=-1;
            y[index]=y_up;
            index++;
        }
        sort(y+1,y+index);
        sort(l+1,l+index);
        build_tree(1,1,index-1);
        double ans=0;
        for (int i=1;i<=index-1;i++)
        {
            ans+=insert(1,l[i].x,l[i].y1,l[i].y2,l[i].flag);
        }
        printf("Test case #%d\n",cnt);
        cnt++;
        printf("Total explored area: %.2f\n\n",ans);
    }
    return 0;
}


你可能感兴趣的:(线段树)