当前位置:网站首页>[acwing] 1268. Simple questions

[acwing] 1268. Simple questions

2022-07-26 05:03:00 Record algorithm solution

Title address :

https://www.acwing.com/problem/content/1270/

There is one n n n Array of elements , Each element is initially 0 0 0. Yes m m m Orders , Or reverse one of the consecutive numbers —— 0 0 0 change 1 1 1, 1 1 1 change 0 0 0( operation 1 1 1), Or ask for the value of an element ( operation 2 2 2). For example, when n = 20 n=20 n=20 when , 10 10 10 The instructions are as follows :
 Insert picture description here
Input format :
The first line contains two integers n , m n,m n,m, Represents the length of the array and the number of instructions ;
following m m m That's ok , The first number of each line t t t Indicates the type of operation :
if t = 1 t=1 t=1, Then there are two numbers L , R L,R L,R, Indicates the interval [ L , R ] [L,R] [L,R] Every number of is reversed ;
if t = 2 t=2 t=2, Then there is only one number i i i, Subscript indicating inquiry ( Array index from 1 1 1 Start ).

Output format :
Each operation 2 2 2 Output one line ( Not 0 0 0 namely 1 1 1), Indicates each operation 2 2 2 Answer .

Data range :
1 ≤ n ≤ 1 0 5 1≤n≤10^5 1n105
1 ≤ m ≤ 5 × 1 0 5 1≤m≤5×10^5 1m5×105
Guarantee L ≤ R L≤R LR

Because flipping is equivalent to non carry addition , Thus equivalent to XOR , So let's consider a differential array , And maintain it with a tree array . The difference of this difference array is XOR ( namely A A A The differential array of c [ i ] = A [ i ] ∧ A [ i − 1 ] c[i]=A[i]\land A[i-1] c[i]=A[i]A[i1]). So flip A [ l : r ] A[l:r] A[l:r] Equivalent to c [ l ] = c [ l ] ∧ 1 , c [ r + 1 ] = c [ r + 1 ] ∧ 1 c[l]=c[l]\land 1, c[r+1]=c[r+1]\land 1 c[l]=c[l]1,c[r+1]=c[r+1]1, Asking is equivalent to finding prefix XOR and . The code is as follows :

#include <iostream>
#define lowbit(x) (x & -x)
using namespace std;

const int N = 1e5 + 10;
int n, m;
int tr[N];

void add(int k, int x) {
    
  for (; k <= n; k += lowbit(k)) tr[k] ^= x;
}

int sum(int k) {
    
  int res = 0;
  for (; k; k -= lowbit(k)) res ^= tr[k];
  return res;
}

int main() {
    
  scanf("%d%d", &n, &m);
  while (m--) {
    
    int t, l, r, k;
    scanf("%d", &t);
    if (t == 1) {
    
      scanf("%d%d", &l, &r);
      add(l, 1);
      add(r + 1, 1);
    } else {
    
      scanf("%d", &k);
      printf("%d\n", sum(k));
    }
  }
}

Time complexity of each operation O ( log ⁡ n ) O(\log n) O(logn), Space O ( n ) O(n) O(n).

原网站

版权声明
本文为[Record algorithm solution]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/207/202207260458072865.html