Use find_k_th of the tree array to find the minimum position where sum is K. The time complexity is O (log (n ))
/*************************************** **************************************** # Author: neo Fung # Email: neosfung@gmail.com # Last modified: # filename: poj2892 HDU 1540 tunnel warfare. CPP # Description: Use find_k_th of the tree array to find the minimum position where sum is K. The time complexity is O (log (n )) **************************************** **************************************/# ifdef _ msc_ver # define debug # endif # include <FS Tream> # include <stdio. h> # include <iostream> # include <string. h> # include <string> # include <limits. h> # include <algorithm> # include <stack> # include <math. h ># define Max 50010 # define lowbit (x) (X & (-x) using namespace STD; int C [Max]; stack <int> order; int getsum (int x) {int sum = 0; For (INT I = x; I> 0; I-= lowbit (I) sum ++ = C [I]; return sum;} void updata (const Int & X, const Int & N, const Int & Val) {for (INT I = x; I <= N; I + = lowb It (I) c [I] + = val;} // locate int find_k_th (int K, const Int & N, const Int & logn) at the position smaller than K) {int CNT = 0, cur = 0; For (INT I = logn; I> = 0; -- I) {cur + = (1 <I ); if (cur> N | CNT + C [cur]> = k) cur-= (1 <I); else CNT ++ = C [cur];} return cur + 1;} int main (void) {# ifdef debug freopen (".. /stdin.txt "," r ", stdin); freopen (".. /stdout.txt "," W ", stdout); # endif int n, m, X; char ch; while (~ Scanf ("% d", & N, & M) {memset (C, 0, sizeof (c); While (! Order. empty () Order. pop (); N + = 2; updata (1, n, 1); // number 1 and number n + 2 are used as the sentry, and only use [2, n + 1] records valid data; updata (N, N, 1); int logn = int (log (n + 1.0)/log (2.0); While (M --) {getchar (); scanf ("% C", & Ch); If (CH = 'D') {scanf ("% d", & X ); ++ X; Order. push (x); updata (x, N, 1);} else if (CH = 'R') {x = order. top (); Order. pop (); updata (x, N,-1) ;}else {scanf ("% d", & X); ++ X; int sum = getsum (x ), pre = find_k_th (sum, N, logn), next = find_k_th (sum + 1, N, logn); If (pre! = X) printf ("% d \ n", next-pre-1); else printf ("0 \ n") ;}} return 0 ;}