Summer Training day6 coseforces339D 线段树、位操作
Xenia the beginner programmer has a sequence?a, consisting of?2n?non-negative integers:?a1,?a2,?...,?a2n. Xenia is currently studying bit operations. To better understand how they work, Xenia decided to calculate some value?v?for?a.
Namely, it takes several iterations to calculate value?v. At the first iteration, Xenia writes a new sequence?a1?or?a2,?a3?or?a4,?...,?a2n?-?1?or?a2n, consisting of?2n?-?1?elements. In other words, she writes down the bit-wise OR of adjacent elements of sequence?a. At the second iteration, Xenia writes the bitwise?exclusive?OR of adjacent elements of the sequence obtained after the first iteration. At the third iteration Xenia writes the bitwise OR of the adjacent elements of the sequence obtained after the second iteration. And so on; the operations of bitwise exclusive OR and bitwise OR alternate. In the end, she obtains a sequence consisting of one element, and that element is?v.
Let's consider an example. Suppose that sequence?a?=?(1,?2,?3,?4). Then let's write down all the transformations?(1,?2,?3,?4)??→?(1?or?2?=?3,?3?or?4?=?7)??→??(3?xor?7?=?4). The result is?v?=?4.
You are given Xenia's initial sequence. But to calculate value?v?for a given sequence would be too easy, so you are given additional?mqueries. Each query is a pair of integers?p,?b. Query?p,?b?means that you need to perform the assignment?ap?=?b. After each query, you need to print the new value?v?for the new sequence?a.
InputThe first line contains two integers?n?and?m?(1?≤?n?≤?17,?1?≤?m?≤?105). The next line contains?2n?integers?a1,?a2,?...,?a2n?(0?≤?ai?<?230). Each of the next?m?lines contains queries. The?i-th line contains integers?pi,?bi?(1?≤?pi?≤?2n,?0?≤?bi?<?230)?— the?i-th query.
OutputPrint?m?integers — the?i-th integer denotes value?v?for sequence?a?after the?i-th query.
Examples input 2 4 1 6 3 5 1 4 3 4 1 2 1 2 output 1 3 3 3 NoteFor more information on the bit operations, you can follow this link:?http://en.wikipedia.org/wiki/Bitwise_operation
題解:把題目給出的所有元素構建一顆線段樹,對于更新操作,類似于線段樹的操作,從下往上處理線段樹的子區間,用當前層的深度來確定對每一層實施什么樣的擦操作。然后pushup操作更新當前區間。時間復雜度O(logn)代碼:
#include <iostream> #include <cstdio> using namespace std; int a[1<<18]; int n,m; int dfs(int x,int dep,int l,int r){if(l == r){return a[x];}int mid = (l + r) / 2;int ls = dfs(2*x,dep+1,l,mid);int rs = dfs(2*x + 1,dep + 1,mid + 1,r);if((n - dep) % 2 == 0){//ora[x] = ls | rs;}else{a[x] = ls ^ rs;}return a[x]; } int main(){scanf("%d%d",&n,&m);for(int i = 0;i < (1<<n);i++){int tmp;scanf("%d",&tmp);a[(1<<n)+i] = tmp;}dfs(1,1,1,(1<<n));while(m--){int p,b;scanf("%d%d",&p,&b);int fa = (1<<n) + p - 1;a[fa] = b;int dep = 0;while(fa != 1){fa = fa / 2;if(dep % 2 == 0)a[fa] = a[fa*2] | a[fa*2+1];elsea[fa] = a[fa*2] ^ a[fa*2+1];dep ++;}printf("%d\n",a[1]);}return 0; }
總結
以上是生活随笔為你收集整理的Summer Training day6 coseforces339D 线段树、位操作的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 韵母的分类 韵母的分类是什么
- 下一篇: Div1 小A抓小B tarjan双连通