線段樹 矩形並周長 picture

來源:互聯網
上載者:User

線段樹 我還是首推胡浩大牛的部落格http://www.notonlysuccess.com/

線段樹中掃描線一直是我比較吃力的一種題。矩形面積並,周長並,特別是周長並,一直無法解決,想不明白,現在終於做出來一個周長並的題目了, 是不是我的線段樹水平又有了一點提高呢?

代碼不長,寫起來老麻煩了!

周長並與面積並不同的是,周長並需要記錄豎著的邊的情況。也就是說,需要記錄邊的合并問題,代碼中分別使用lbd和rbd記錄是否有邊,如果合并的都有邊,那麼,合并之後的豎著的邊的總數就要減2.

#include <iostream>#include <stdio.h>#include <string.h>#include <algorithm>using namespace std;#define N 10010struct note{    int a,b,h,s;    note(){}    note(int l,int r,int c,int d):a(l) , b(r) , h(c) , s(d) {}}data[N];///線段樹#define lson l ,m ,rt<<1#define rson m+1,r,rt<<1|1#define fmid (l+r)>>1#define M 22222int len[M<<2],memseg[M<<2],lbd[M<<2],rbd[M<<2],cnt[M<<2];void Push_up(int rt,int l,int r){    if(cnt[rt])    {        lbd[rt] = rbd[rt] = 1;        memseg[rt] = 2;        len[rt] = r-l+1;    }else if(l == r) lbd[rt] = rbd[rt] = memseg[rt] = len[rt] = 0;    else    {        lbd[rt] = lbd[rt<<1];        rbd[rt] = rbd[rt<<1|1];        len[rt] = len[rt<<1] + len[rt<<1|1];        memseg[rt] = memseg[rt<<1] + memseg[rt<<1|1];        if(rbd[rt<<1] && lbd[rt<<1|1] ) memseg[rt] -= 2;    }}/***矩形有個特點,已經出現的更新,必然會再次出現,這樣的話,延遲標記也就可以不用push_down()!*/void update(int lx,int rx,int s,int l,int r,int rt){    if(lx <= l && rx >= r)    {        cnt[rt] += s;        Push_up(rt,l,r);        return;    }    int m = fmid;    if(lx <= m) update(lx,rx,s,lson);    if(m < rx) update(lx,rx,s,rson);    Push_up(rt,l,r);}//////////////////////////////////////bool cmp(const note a,const note b){    return a.h < b.h || (a.h == b.h && a.s < b.s); ///?????排序的時候可以不對s進行比較}int main(){    int n;    while(~scanf("%d",&n))    {        int x,y,xx,yy;        int ll = 10000,rr = -10000;        int m = 0;        for(int i = 0;i < n;i++)        {            scanf("%d%d%d%d",&x,&y,&xx,&yy);            ll = min(ll,x);            rr = max(rr,xx);            data[m++] = note(x,xx,y,1);            data[m++] = note(x,xx,yy,-1);        }        sort(data,data+m,cmp);        data[m].h = data[m-1].h;        int ret = 0,last = 0;        for(int i = 0;i < m;i++)        {            if(data[i].a != data[i].b) update(data[i].a ,data[i].b-1,data[i].s,ll,rr,1);            ret += abs(len[1] - last);            ret += memseg[1] * (data[i+1].h - data[i].h);            last = len[1];        }        printf("%d\n",ret);    }    return 0;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.