Luo Gu P5057 [CQOI2006] simple question (Fenwick tree)

Ok...

 

Topic link: https: //www.luogu.org/problem/P5057

 

This question was first discovered only 0 and 1, so definitely related to binary. This question needs to support the interval and then found a single point of change and query operations, so the first thought is the difference array of exclusive or meaning, so he wrote himself a differential array, really good writing, but very slow (I may not write excellent), the following is the difference of the code under the exclusive or meaning five are:

 1 #include<cstdio>
 2 #include<iostream>
 3 
 4 using namespace std;
 5 
 6 int a[100005], b[100005];
 7 
 8 int main(){
 9     int n, m, t, l, r, x;
10     scanf("%d%d", &n, &m);
11     for(int i = 1; i <= n; i++) b[i] = a[i] ^ a[i - 1];
12     for(int i = 1; i <= m; i++){
13         scanf("%d", &t);
14         if(t == 1){
15             scanf("%d%d", &l, &r);
16             b[l] ^= 1;
17             b[r + 1] ^= 1;
18             for(int i = 1; i <= n; i++)
19                 a[i] = a[i - 1] ^ b[i]; 
20         }
21         else{
22             scanf("%d", &x);
23             printf("%d\n", a[x]);
24         }
25     }
26     return 0;
27 }
28             
50 minutes - the difference

Obviously, I wrote about the difference in time complexity O (mn), so a timeout ...

 

The positive solution is to use an array to maintain the tree, because the tree change intervals and arrays support a single point of inquiry. Note After a single point of inquiry, is also the title of the most magical place, a query of decimal 2%, you can get the last one is the answer to its binary (can also be understood as odd operation will change, even number of times operation does not change)

 

AC Code:

#include<cstdio>
#include<iostream>

using namespace std;

int n, t[1000005];

inline int lowbit(int x){
    return x & -x;
}//lowbit

inline void change(int x, int k){
    while(x <= n){
        t[x] += k;
        x += lowbit(x);
    }
    return;
}//区间更改

inline int check(int x){
    int ans = 0;
    while(x > 0){
        ans += t[x];
        x -= lowbit(x);
    }
    return ans;
}//单点查询

int main(){
    int m, l, r, f, d;
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= m; i++){
        scanf("%d", &f);
        if(f == 1){
            scanf("%d%d", &l, &r);
            change(l, 1);
            change(r + 1, -1);
        }
        else{
            scanf("%d", &d);
            printf("%d\n", check(d) % 2);//核心
        }
    }
    return 0;
}
AC Code

 

Guess you like

Origin www.cnblogs.com/New-ljx/p/11267274.html