[線段樹練習2] 影子的寬度 - 統計標記個數


題目描述

桌子上零散地放着若干個盒子,盒子都平行於牆。桌子的後方是一堵牆。如圖所示。現在從桌子的前方射來一束平行光,把盒子的影子投射到了牆上。問影子的總寬度是多少?


輸入格式

第1行:3個整數L,R,N。-100000 <=L<=R<= 100000,表示牆所在的區間;1<=N<=100000,表示盒子的個數
接下來N行,每行2個整數BL, BR,-100000 <=BL<=BR<= 100000,表示一個盒子的左、右端點


輸出格式

輸出僅爲一個整數W,表示影子的總寬度。


樣例數據

樣例輸入

1 10 3
3 5
1 4
7 8

樣例輸出

5


題目分析

統計標記個數(區間修改區間查詢)
data直接置1不管懶標記
queryLeft~Right隨便亂查
注意要加偏移量
因爲C++的負數向0取整,會導致堆式編號出錯


源代碼

#include<algorithm>
#include<iostream>
#include<iomanip>
#include<cstring>
#include<cstdlib>
#include<vector>
#include<cstdio>
#include<cmath>
#include<queue>
using namespace std;
inline const int Get_Int() {
    int num=0,bj=1;
    char x=getchar();
    while(x<'0'||x>'9') {
        if(x=='-')bj=-1;
        x=getchar();
    }
    while(x>='0'&&x<='9') {
        num=num*10+x-'0';
        x=getchar();
    }
    return num*bj;
}
const int maxn=600000;
struct Tree { //修改區間 查詢區間 
    int left,right,data;
};
struct Segment_Tree { //統計標記個數 
    Tree tree[maxn*4];
    int sum;
    void build(int index,int Left,int Right) {
        tree[index].left=Left;
        tree[index].right=Right;
        tree[index].data=0;
        if(Left==Right)return;
        int mid=(Left+Right)/2;
        build(2*index,Left,mid);
        build(2*index+1,mid+1,Right);
    }
    void modify(int index,int Left,int Right) { //增加區間的值
        if(Right<tree[index].left||Left>tree[index].right)return; //不相交
        if(tree[index].data)return;
        if(Left<=tree[index].left&&Right>=tree[index].right) { //完全包含
            tree[index].data=1;
            return;
        }
        modify(index*2,Left,Right);
        modify(index*2+1,Left,Right);
    }
    void init() { //注意多次詢問一定要調用
        sum=0;
    }
    void Query(int index,int Left,int Right) { //查詢區間值
        if(Right<tree[index].left||Left>tree[index].right)return; //不相交
        if(tree[index].data) {
            sum+=tree[index].right-tree[index].left+1;
            return;
        }
        Query(index*2,Left,Right);
        Query(index*2+1,Left,Right);
    }
};
Segment_Tree st;
int Left,Right,n,Delta;
int main() {
    Left=Get_Int();
    Delta=Left-1;
    Left-=Delta;
    Right=Get_Int()-Delta-1;
    st.build(1,Left,Right);
    n=Get_Int();
    for(int i=1; i<=n; i++) {
        int l=Get_Int()-Delta,r=Get_Int()-Delta;
        if(l>r)continue;
        st.modify(1,l,r-1);
    }
    st.init();
    st.Query(1,Left,Right);
    printf("%d\n",st.sum);
    return 0;
}

發佈了169 篇原創文章 · 獲贊 31 · 訪問量 7萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章