马蜂唯一好看的一次
线段树模板:
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
const int N = 1e5 + 10;
int a[N]; //a是原始数组
struct node
{
int left, right; //这个节点管辖的区间范围
int data; //这个节点本身储存的数据
int lazy;//这个节点的修改次数
} tree[N << 2]; //开4倍空间
void pushdown(int p) //标志性的线段树代码
{
if (tree[p].lazy)
{
int mid = tree[p].left + tree[p].right >> 1;
tree[p << 1].lazy += tree[p].lazy; //lazy传给左儿子
tree[p << 1].data += tree[p].lazy * (mid - tree[p << 1].left + 1); //更新左儿子的data
tree[p << 1 | 1].lazy += tree[p].lazy; //lazy传给右儿子
tree[p << 1 | 1].data += tree[p].lazy * (tree[p << 1 | 1].right - mid); //更新右儿子的data
tree[p].lazy = 0; //父节点的lazy清零
}
}
void build(int p, int L, int R) //把区间[L,R]建成以p为根节点的线段树
{
tree[p].left = L;
tree[p].right = R;
tree[p].lazy = 0;
if (L == R) //走到了叶节点
{
tree[p].data = a[L]; //走之前把值带回来
return;
}
int mid = L + R >> 1; //(L+R)/2
build(p << 1, L, mid); //递归建左子树
build(p << 1 | 1, mid + 1, R); ////递归建右子树
tree[p].data = tree[p << 1].data + tree[p << 1 | 1].data; //回溯时维护数据信息
}
int query(int p, int L, int R) //在以p为根节点的线段树中,查询区间[L,R]
{
if (tree[p].left >= L && tree[p].right <= R)
return tree[p].data; //完全包含关系,直接拿着,不需要再递归下去
pushdown(p); //补充lazy
int res = 0;
if (tree[p << 1].right >= L) res += query(p << 1, L, R); //往左子树递归查询
if (tree[p << 1 | 1].left <= R) res += query(p << 1 |1, L, R); //往右子树递归查询
return res;
}
void modify(int p, int L, int R, int x) //修改以p为根节点的区间,修改范围[L,R]改为+x
{
if (tree[p].left >= L && tree[p].right <= R)
{
tree[p].lazy += x; //修改lazy域
tree[p].data += (tree[p].right - tree[p].left + 1) * x; //修改data域
return;
}
pushdown(p); //补充lazy
if (tree[p << 1].right >= L) modify(p << 1, L, R, x); //左子树递归修改
if (tree[p << 1 | 1].left <= R) modify(p << 1 | 1, L, R, x); //右子树递归修改
tree[p].data = tree[p << 1].data + tree[p << 1 | 1].data;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
return 0;
}
线段树练习:
https://www.luogu.com.cn/problem/P3372
https://www.luogu.com.cn/problem/P3368
马蜂依旧不好看
树状数组模板:
#include<bits/stdc++.h>
#define int long long
#define endl '\n'
using namespace std;
int a[200015],n,m;
int l(int x){
return x&-x;
}
void b(int x,int k){ //修改
while(x<=n){
a[x]+=k;
x+=l(x);
}
}
int q(int y){ //查询
int res=0;
while(y){
res+=a[y];
y-=l(y);
}
return res;
}
signed main()
{
ios::sync_with_stdio(0);
cin.tie(0);
cout.tie(0);
return 0;
}