cf div2 234 E
Inna is fed up with jokes about female logic. So she started using binary logic instead.
Inna has an array of n elements a1[1], a1[2], ..., a1[n]. Girl likes to train in her binary logic, so she does an exercise consisting of nstages: on the first stage Inna writes out all numbers from array a1, on the i-th (i ≥ 2) stage girl writes all elements of array ai, which consists of n - i + 1 integers; the k-th integer of array ai is defined as follows: ai[k] = ai - 1[k] AND ai - 1[k + 1]. Here AND is bit-wise binary logical operation.
Dima decided to check Inna's skill. He asks Inna to change array, perform the exercise and say the sum of all elements she wrote out during the current exercise.
Help Inna to answer the questions!
The first line contains two integers n and m (1 ≤ n, m ≤ 105) — size of array a1 and number of Dima's questions. Next line contains nintegers a1[1], a1[2], ..., a1[n] (0 ≤ ai ≤ 105) — initial array elements.
Each of next m lines contains two integers — Dima's question description. Each question consists of two integers pi, vi (1 ≤ pi ≤ n; 0 ≤ vi ≤ 105). For this question Inna should make a1[pi] equals vi, and then perform the exercise. Please, note that changes are saved from question to question.
For each question print Inna's answer on a single line.
3 4
1 1 1
1 1
2 2
3 2
1 2
6
4
7
12
原来以为要各种优化,谁知道只要直接暴力就可以了,汗!
首先把这个序列拆成二进制数,一位一位的看。
对于每个p v ,对于每个二进制位,从 p - 1 往下搜连续的1 的个数, 从 p + 1 往上搜连续的1 的个数,最后代公式
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 6 using namespace std; 7 typedef long long ll; 8 9 #define maxn 100005 10 11 int n,m,p,v; 12 int a[maxn]; 13 ll ans = 0; 14 15 int main () { 16 // freopen("sw.in","r",stdin); 17 18 scanf("%d%d",&n,&m); 19 20 for(int i = 1; i <= n; ++i) { 21 scanf("%d",&a[i]); 22 } 23 24 for(int dig = 0; dig < 18; ++dig) { 25 for(int i = 1; i <= n; ++i) { 26 if(a[i] >> dig & 1) { 27 int j; 28 for(j = i; j <= n && ((a[j] >> dig) & 1); ++j ) ; 29 ans += (1 << dig) * (ll)(j - i) * (j - i + 1) / 2; 30 i = j; 31 } 32 33 } 34 35 } 36 37 for(int i = 1; i <= m; ++i) { 38 scanf("%d%d",&p,&v); 39 ll l = 0, r = 0; 40 for(int dig = 0; dig < 18; ++dig) { 41 int j; 42 for(j = p - 1; ((a[j] >> dig) & 1) && j >= 1; --j); 43 // printf(" j = %d\n",j); 44 l = p - 1 - j; 45 for(j = p + 1; ((a[j] >> dig) & 1) && j <= n; ++j); 46 r = j - (p + 1); 47 //printf("dig = %d l = %d r = %d\n",dig,l,r); 48 if((a[p] >> dig & 1) ^ (v >> dig & 1)) { 49 ll t = (a[p] >> dig & 1) ? 1 : -1; 50 ans += (1 << dig) * t * (l * (l + 1) / 2 + r * (r + 1) / 2 - 51 (l + r + 2) * (l + r + 1) / 2); 52 } 53 } 54 a[p] = v; 55 printf("%I64d\n",ans); 56 57 58 59 } 60 return 0; 61 }
计算变化的值以修改 ans.