Use a tree array to calculate the minimum K value. Pay attention to the boundary.
# Define n 50005int C [N]; int lowbit (int x) {return X & (-x);} void add (int x, int V) {While (x <n) {C [x] + = V; x + = lowbit (x) ;}} int sum (int x) {int ans = 0; while (x) {ans + = C [X]; X-= lowbit (x);} return ans;} int find_k (int K) {int ans = 0, CNT = 0; For (INT I = Log (double (N-1)/log (2.0); I> = 0; I --) {ans + = (1 <I); If (ANS> = n | CNT + C [ANS]> = K) {ANS-= (1 <I);} else CNT + = C [ANS];} return ans + 1;} int main () {int n, m; while (SC ANF ("% d", & N, & M )! =-1) {int I, j; memset (C, 0, sizeof (c); stack <int> st; add (); // pay attention to the boundary, move back one add (n + 2, 1); // same as while (M --) {char STR [2]; scanf ("% s", STR); int Pos; if (STR [0] = 'D') {scanf ("% d", & Pos); POS ++; add (Pos, 1); ST. push (POS);} else if (STR [0] = 'R') {pos = ST. top (); ST. pop (); add (Pos,-1) ;}else {scanf ("% d", & Pos); POS ++; int K = sum (POS ); int A = find_k (k); int B = find_k (k + 1); If (k-sum (pos-1) = 1) {printf ("0 \ n");} else printf ("% d \ n", b-a-1) ;}} return 0 ;}