ACdream 1055 Crayon (離散化+樹狀數組)

題目鏈接:
ACdream 1055

題意:
給你 n 個操作,這些操作可以畫一條區間大小爲 [L,R] 的線段,可以刪去第 i 條加入的線段,也可以詢問區間 [L,R] 中有多少個整數點是這些線段共有的。

題解:
先離散化處理一下,再用樹狀數組維護一下區間變化即可。
詳細看代碼。

AC代碼:

#include <bits/stdc++.h>
using namespace std;
struct data
{
    int x,y;
    char ch;
}d[123456];
int tree[200010][2];
int has[200010],all;
int lowbit(int x)
{
    return x&(-x);

}

void update(int x,int val,int k)
{
    while(x<=all)
    {
        tree[x][k] += val;
        x+=lowbit(x);
    }
}
int query(int x,int k)
{
    int res = 0 ;
    while(x)
    {
        res += tree[x][k];
        x -= lowbit(x); 
    }
    return res;
}
int solve(int l,int r)
{
    return query(r,0) - query(l-1,1);
}
int main()
{
    int n;
    while(~scanf("%d",&n))
    {
        all = 0;
        for(int i=1;i<=n;i++)
        {
            getchar();
            scanf("%c",&d[i].ch);
            if(d[i].ch=='C')
            {
                scanf("%d",&d[i].x);
                has[all++] = d[i].x;
            }
            else // D , Q 
            {
                scanf("%d%d",&d[i].x,&d[i].y);
                has[all++] = d[i].x;
                has[all++] = d[i].y;
            }
        }
        sort(has,has+all);
        all = unique(has,has+all) - has;
        memset(tree,0,sizeof(tree));
        int cnt = 0;
        for(int i=1;i<=n;i++)
        {
            if(d[i].ch =='D')//draw 
            {
                int l = lower_bound(has, has+all, d[i].x) - has;
                int r = lower_bound(has, has+all, d[i].y) - has;
                update(l+1,1,0);
                update(r+1,1,1);
                d[++cnt] = d[i];
            }
            else if(d[i].ch == 'Q') //query 
            {
                int l = lower_bound(has,has+all,d[i].x) - has;
                int r = lower_bound(has,has+all,d[i].y) - has;
                printf("%d\n",solve(l+1,r+1));
            }
            else if(d[i].ch == 'C') //clear 
            {
                int l = lower_bound(has,has+all,d[d[i].x].x) - has;
                int r = lower_bound(has,has+all,d[d[i].x].y) - has;
                update(l+1,-1,0);
                update(r+1,-1,1);
            }
        }
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章