[题解]AT_abc106_d [ABC106D] AtCoder Express 2

思路

问题本质上就是一个在一段区间中找完整线段的数量。

我们先不考虑所有 \(l_i\) 对答案的限制,那么,我们的答案就应该是 \(1 \sim q\) 线段的数量减去 \(1 \sim (p - 1)\) 的数量,这个东西可以直接用树状数组维护。

然后,再来考虑 \(l_i\) 对答案的限制。如果线段 \(i\) 能对答案产生贡献,当且仅当 \(p \leq l_i \wedge r_i \leq q\)

因此,我们如果每次只将 \(l_i \geq p\) 的线段加入树状数组,就可以保证答案正确了,但是时间复杂度是 \(\Theta(qm \log n)\),考虑优化。

如果我们对于每一次查询时对于树状数组的操作只加不减,那么,时间复杂度可以优化成 \(\Theta(q \log n)\)

于是我们直接离线搞,将线段和询问都按照左端点为第一关键字从大到小排序,那么,我们在前一次询问存在在树状数组的元素就不用删除,只需要将新的元素加入即可。

Code

#include <bits/stdc++.h>  
#define re register  
  
using namespace std;  
  
const int N = 510,M = 2e5 + 10;  
int n,m,q;  
int ans[M];  
  
struct array{  
    int l;  
    int r;  
  
    bool operator <(const array &t)const{  
        return l > t.l;  
    }  
}arr[M];  
  
struct point{  
    int l;  
    int r;  
    int id;  
  
    bool operator <(const point &t)const{  
        return l > t.l;  
    }  
}Q[M];  
  
struct BIT{  
    int tr[N];  
  
    inline int lowbit(int x){  
        return x & -x;  
    }  
  
    inline void modify(int x,int k){  
        for (re int i = x;i <= n;i += lowbit(i)) tr[i] += k;  
    }  
  
    inline int query(int x){  
        int res = 0;  
        for (re int i = x;i;i -= lowbit(i)) res += tr[i];  
        return res;  
    }  
}tree;  
  
inline int read(){  
    int r = 0,w = 1;  
    char c = getchar();  
    while (c < '0' || c > '9'){  
        if (c == '-') w = -1;  
        c = getchar();  
    }  
    while (c >= '0' && c <= '9'){  
        r = (r << 1) + (r << 3) + (c ^ 48);  
        c = getchar();  
    }  
    return r * w;  
}  
  
int main(){  
    n = read();  
    m = read();  
    q = read();  
    for (re int i = 1;i <= m;i++){  
        arr[i].l = read();  
        arr[i].r = read();  
    }  
    for (re int i = 1;i <= q;i++){  
        Q[i].l = read();  
        Q[i].r = read();  
        Q[i].id = i;  
    }  
    sort(arr + 1,arr + m + 1);  
    sort(Q + 1,Q + q + 1);  
    int idx = 1;  
    for (re int i = 1;i <= q;i++){  
        int ql = Q[i].l;  
        int qr = Q[i].r;  
        while (arr[idx].l >= ql && idx <= m){  
            tree.modify(arr[idx].r,1);  
            idx++;  
        }  
        ans[Q[i].id] = tree.query(qr) - tree.query(ql - 1);  
    }  
    for (re int i = 1;i <= q;i++) printf("%d\n",ans[i]);  
    return 0;  
}  
posted @ 2024-06-22 01:27  WBIKPS  阅读(30)  评论(0)    收藏  举报