Test instructions: Given n line segments, the two endpoints L and r of each segment are integers. Then give M queries, each asking for a given two intervals [l1,r1] and [L2,R2], ask how many line segments meet: L1≤L≤R1, l2≤r≤r2?
The solution, using the offline approach, first all the line segments and the query interval are all saved. Then split each inquiry [L1,R1][L2,R2] into two, l1-1, [L2,R2] and R1,[L2,R2]. x, [L2,R2] represents the starting point L <= x, the end point R satisfies the number of line segments of L2 <= R <= R2, then the answer to each query is the value of R1,[L2,R2]-l1-1, [L2,R2]. Then we need to query the value of X,[L2,R2].
Sorts all the segments by their starting point, and sorts all newly generated queries by X. After the scan, for each query, the loop is l>x until the beginning of the line, otherwise the value of the segment at the end of the tree array is added 1. At this point, the prefix of the R2 position of the tree array is computed and the prefix minus the l1-1 position is the answer. See the code:
#include <cstdio>#include<algorithm>#include<cstring>using namespacestd;#defineN 100100structline{ints, t; BOOL operator< (ConstLine a)Const { returns <A.S; }}p[n];structrange{ints, id; Line T; BOOL operator< (ConstRange a)Const { returns <A.S; }}rg[2*N];intV[n];intlbintx) {returnx&-x;}voidAddintID) { while(ID <N) {V[id]++; ID+=lb (id); }}int Get(intID) { if(id = =0)return 0; returnv[id]+Get(id-lb (id));}intAns[n];intMain () {intN, M, I, J; while(~SCANF ("%d", &N)) { for(i =0; I < n; i++) scanf ("%d%d", &p[i].s, &p[i].t); scanf ("%d", &m); intS1, T1, S2, t2, C =0; for(i =0; I < m; i++) {scanf ("%d %d%d%d", &s1, &t1, &S2, &T2); Rg[c].s= s1-1; Rg[c].t.s= s2, rg[c].t.t =T2; Rg[c].id= C + +; Rg[c].s=T1; Rg[c].t.s= s2, rg[c].t.t =T2; Rg[c].id= C + +; } sort (p, p+N); Sort (RG, RG+c); memset (ans,0,sizeof(ans)); memset (V,0,sizeof(v)); for(inti =0, j =0; I < C; i++) { while(J < n && P[j].s <=rg[i].s) Add (p[j++].t); intTM =Get(RG[I].T.T)-Get(rg[i].t.s-1); if(rg[i].id&1) Ans[rg[i].id/2] +=TM; ElseAns[rg[i].id/2] -=TM; } for(inti =0; I < m; i++) printf ("%d\n", Ans[i]); } return 0;}
TOJ 4105 Lines Counting (tree-like array)