codeforces 339 D. Xenia and Bit Operations(线段树)

题目链接

题意:给出n和m,初始给出1<<n个数,先相邻的两个数进行或操作(a[1]^a[2],a[3]^a[4]...),得到的新数列再相邻的两个数进行异或操作

最后得到一个数,即为答案。现在给出m个操作,每个操作两个数p,b,表示令a[p]=b,每次变化后输出最终的结果。

思路:线段树。这道题让我学到了,线段树的数组tree[i]存储的信息可能不唯一,可以不同层存储的是不同的信息。

比如这道题中,距离叶子节点距离为奇数的点存储的是或操作的结果,距离叶子节点距离为偶数的点存储的是异或操作的结果。

还需要注意的是,build和update操作都是从顶向下,最后一个操作是异或还是或取决于n的奇偶性,记得判断。

 1/* ***********************************************
 2Author :111qqz
 3Created Time :Mon 05 Sep 2016 12:56:34 AM CST
 4File Name :code/cf/problem/339D.cpp
 5************************************************ */
 6#include <cstdio>
 7#include <cstring>
 8#include <iostream>
 9#include <algorithm>
10#include <vector>
11#include <queue>
12#include <set>
13#include <map>
14#include <string>
15#include <cmath>
16#include <cstdlib>
17#include <ctime>
18#define fst first
19#define sec second
20#define lson l,m,rt<<1
21#define rson m+1,r,rt<<1|1
22#define ms(a,x) memset(a,x,sizeof(a))
23typedef long long LL;
24#define pi pair < int ,int >
25#define MP make_pair
26using namespace std;
27const double eps = 1E-8;
28const int dx4[4]={1,0,0,-1};
29const int dy4[4]={0,-1,1,0};
30const int inf = 0x3f3f3f3f;
31const int N=1<<18;
32int tree[N<<2];
33int n,m;
34void PushUp(int rt,int state)
35{
36    if (state==-1)
37	tree[rt] = tree[rt<<1]|tree[rt<<1|1];
38    else tree[rt] = tree[rt<<1]^tree[rt<<1|1];
39}
40void build(int l,int r,int rt,int state)
41{
42    if (l==r)
43    {
44	scanf("%d",&tree[rt]);
45	return ;
46    }
47    int m = (l+r)>>1;
48    build(lson,-state);
49    build(rson,-state);
50    PushUp(rt,state);
51}
52void update( int p,int sc,int l,int r,int rt,int state)
53{
54    if (l==r)
55    {
56	tree[rt] = sc;
57	return;
58    }
59    int m = (l+r)>>1;
60    if (p<=m) update(p,sc,lson,-state);
61    else update(p,sc,rson,-state);
62    PushUp(rt,state);
63}
64int main()
65{
66	#ifndef  ONLINE_JUDGE 
67	freopen("code/in.txt","r",stdin);
68  #endif
69	int state;
70	cin>>n>>m;
71	if (n%2==0) state = 1; //n是树的高度,最后的操作是异或还是或和树的高度的奇偶性有关。
72	else state = -1;
73	n = 1<<n;
74	build(1,n,1,state);
75	while (m--)
76	{
77	    int x,y;
78	    scanf("%d%d",&x,&y);
79	    update(x,y,1,n,1,state);
80	    printf("%d\n",tree[1]);
81	}
82  #ifndef ONLINE_JUDGE  
83  fclose(stdin);
84  #endif
85    return 0;
86}