Title Link: http://poj.org/problem?id=2892
Test instructions: A line of length n, the following m operation
D x means the unit x is destroyed
R means fix the last destroyed unit.
Q X asks the unit and how many contiguous units are around it, and if it's already destroyed, it's 0.
Ideas:
This problem is the classic line tree entry topic, because only a single point of update, does not involve the interval update, with a tree-like array is more concise.
Maintain two tree arrays, one to maintain all 1, and one to maintain all 0.
Flipping (blowing up or repairing) any one unit while modifying both tree arrays is simply a simple process for merging and splitting operations.
In order to find the interval of 1, we use the characteristic of the tree-shaped array to record parts and to search the left and right boundary of the crossing.
#include <vector> #include <stdio.h> #include <stdlib.h> #include <string.h> #include < iostream> #include <algorithm> #include <queue> #include <ctime> #define for (I,A,B) for (int i=a;i <b;i++) #define FORE (I,A,B) for (int i=a;i<=b;i++) #define MST (A, B) memset (A,b,sizeof (a)) #define SCF (a) scanf ("%d" , &a) #define SCFS (a) scanf ("%s", a) #define SCF2 (A, b) scanf ("%d%d", &a,&b) #define SCF3 (a,b,c) scanf ("%d%d%d" , &a,&b,&c) using namespace std;typedef long long int uint;const int N = 50000+5;int m;int mat[n];int s[2][n];// Add to bit treevoid Add (int s[],int i,int x) {for (; I<=m;i + =-i&i) S[i] + = x;} Sum of bit treeint sum (int s[],int i) {int ans = 0; for (; i>=1;i-=-i&i) ans + = s[i]; return ans;} The right boundary of consective value. 1110/0001int NXT (int s[],int j) {int tmp,sj = Sum (s,j); for (int i = j;i<=m;i + =-i&i) if ((tmp = Sum (s,i)) = = = SJ + i-j) j = I,SJ = tmp; Else bReak; if (j = = m) return j; if (Sum (s,j+1)! = sj+1) return j; Return NXT (s,j+1); }//the left boundary of consective value. 0111/1000int Pre (int s[],int j) {int tmp,sj = Sum (s,j); for (int i = j;i>=1;i-=-i&i) if ((tmp = Sum (s,i)) = = = SJ + i-j) j = I,SJ = tmp; else break; if (Sum (s,j-1)! = sj-1) return j+1; if (j = = 1) return j; return pre (S,J-1);} void Flip (int j) {Add (s[mat[j]],j,-1);//Exclude from Self Add (s[mat[j]^1],j,1);//include from Oppo mat[j] ^= 1; }int Lis[n];int Main () {int Q,b,ans;char ch[2];//freopen ("In.txt", "R", stdin);//Freopen ("OUT.txt", "w", stdout); while (SCF2 (m,q)!=eof) {MST (s,0); FORE (j,1,m) Add (s[mat[j] = 1],j,1); Lis[0] = 0; while (q--) {SCFS (CH); if (ch[0]== ' R ') {if (Lis[0]) {if (!mat[lis[lis[0]]) Flip (lis[lis[0] ]); lis[0]--; } CoNtinue; } else SCF (b); if (ch[0]== ' D ') {if (Mat[b]) Flip (b); Lis[++lis[0]] = b; Continue } if (Mat[b]) {int u = NXT (s[1],b); int v = pre (s[1],b); Ans = u-v + 1; } else ans = 0; printf ("%d\n", ans); }}return 0;}
POJ 2892 Tunnel Warfare [tree-shaped array]