Main topic:
The gate is filled with trees of different heights, and every inquiry is if you cut down all trees with a height of no more than Q, then how many contiguous blocks are there?
Thinking Analysis:
Records the number of contiguous blocks left and right consecutively and used to maintain intervals.
That
Seg[num] = seg[num<<1]+seg[num<<1|1];
If the middle part is connected, subtract one.
#include <cstdio> #include <iostream> #include <cstring> #include <algorithm> #define MAXN 50005 #define Lson num<<1,s,mid#define Rson num<<1|1,mid+1,e#define Mid ((s+e) >>1) using namespace Std;int Lsum[maxn<<2],rsum[maxn<<2],seg[maxn<<2];struct tree{int height;int Pos;bool operator < (const Tree &cmp) Const{return height<cmp.height;}} Save[maxn];struct ans{int index;int query;int ans;bool operator < (const ANS & CMP) Const{return query<cmp.query ;}} Prt[maxn];bool cmp_id (Ans A,ans b) {return a.index<b.index;} void pushup (int num,int s,int e) {lsum[num]=lsum[num<<1];if (lsum[num]==mid-s+1) lsum[num]+=lsum[num<<1|1 ];rsum[num]=rsum[num<<1|1];if (Rsum[num]==e-mid) rsum[num]+=rsum[num<<1];seg[num]=seg[num<<1]+ Seg[num<<1|1];if (rsum[num<<1] && lsum[num<<1|1]) seg[num]--;} void build (int num,int s,int e) {if (s==e) {Lsum[num]=rsum[num]=seg[num]=1;return;} Build (Lson); build (Rson);Pushup (num,s,e);} void update (int num,int s,int e,int pos) {if (s==e) {Lsum[num]--, rsum[num]--, Seg[num]--;return;} if (pos<=mid) update (LSON,POS), Else Update (RSON,POS);p ushup (num,s,e);} int main () {int n,q;while (scanf ("%d%d", &n,&q)!=eof) {for (int i=1;i<=n;i++) {scanf ("%d", &save[i]. height); save[i].pos=i;} Sort (save+1,save+1+n), for (int i=1;i<=q;i++) {scanf ("%d", &prt[i].query);p rt[i].index=i;} Sort (prt+1,prt+1+q); build (1,1,n); int dex = 1;for (int i=1;i<=q;i++) {while (Save[dex].height<=prt[i].query & & dex<=n) {update (1,1,n,save[dex].pos);d ex++;} Prt[i].ans = seg[1];} Sort (prt+1,prt+1+q,cmp_id); for (int i=1;i<=q;i++) {printf ("%d\n", Prt[i].ans);}} return 0;}
Hdu 5200 Trees (offline line segment tree)