[線段樹練習3] 盒子的個數 - 統計標記種類


題目描述

桌子上零散地按照後先後順序放着若干個盒子,盒子都平行於牆。桌子的後方是一堵牆。如圖所示。問從桌子前方可以看到多少個盒子?假設人站得足夠遠。


輸入格式

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


輸出格式

輸出僅爲一個整數M,表示可看到的盒子個數。


樣例數據

樣例輸入

1 10 4
3 5
1 4
2 6
7 8

樣例輸出

3


題目分析

統計標記種類(區間修改區間查詢)
我的做法很神奇
直接給區間一個顏色(序號不同顏色不同)
然後查到了就Hash顏色
最後統計Hash
別忘了加偏移量


源代碼

#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;
int Hash[maxn];
struct Tree { //修改區間 查詢區間
    int left,right,data;
};
struct Segment_Tree { //統計標記種類
    Tree tree[maxn*4];
    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 push_down(int index) {
        if(tree[index].data>=0) {
            tree[index*2].data=tree[index*2+1].data=tree[index].data;
            tree[index].data=-1;
        }
    }
    void modify(int index,int Left,int Right,int color) {
        if(Right<tree[index].left||Left>tree[index].right)return; //不相交
        if(Left<=tree[index].left&&Right>=tree[index].right) { //完全包含
            tree[index].data=color;
            return;
        }
        push_down(index);
        modify(index*2,Left,Right,color);
        modify(index*2+1,Left,Right,color);
    }
    void Query(int index,int Left,int Right) {
        if(Right<tree[index].left||Left>tree[index].right)return; //不相交
        if(tree[index].data==0)return;
        if(tree[index].data>0) {
            Hash[tree[index].data]=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-1;
        st.modify(1,l,r,i);
    }
    st.Query(1,Left,Right);
    int sum=0;
    for(int i=1; i<=n; i++)
        if(Hash[i])sum++;
    printf("%d\n",sum);
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章