题目链接
题目AC代码:
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 2e5 + 10;
int m, p;
struct Node
{
int l, r;
int v; //区间最大值
}tr[4 * N];
void pushup(int u) //由子节点确定父节点
{
tr[u].v = max(tr[u << 1].v, tr[u << 1 | 1].v);
}
void build(int u, int l, int r)
{
tr[u] = {l, r};
if(l == r) return ;
int mid = (l + r) >> 1;
build(u << 1, l, mid);
build(u << 1 | 1, mid + 1, r);
}
int query(int u, int l, int r)
{
if(tr[u].l >= l && tr[u].r <= r) return tr[u].v;
int mid = tr[u].l + tr[u].r >> 1;
int v = 0;
if(l <= mid) v = query(u << 1, l, r);
if(r > mid) v = max(query(u << 1 | 1, l, r), v);
return v;
}
void modify(int u, int x, int v)
{
if(tr[u].l == tr[u].r) tr[u].v = v;
else
{
int mid = (tr[u].l + tr[u].r) >> 1;
if(x <= mid) modify(u << 1, x, v);
else modify(u << 1 | 1, x, v);
pushup(u);
}
}
signed main()
{
cin >> m >> p;
int n = 0, last = 0;;
build(1, 1, m);
while(m--)
{
char s[2];
int x;
cin >> s >> x;
if(*s == 'Q')
{
last = query(1, n - x + 1, n);
cout << last << endl;
}
else
{
modify(1, n + 1, (last + x) % p);
n++;
}
}
return 0;
}
线段树维护的区间关系,他将一个一个区间划分为不同的两个区间,层层递归,当然,他的运用范围挺广泛的。
#include <bits/stdc++.h>
#define int long long
using namespace std;
const int N = 1e5 + 10;
struct tre
{
int l, r; //边界
int mx; //区间最大值
} tr[4 * N];
int a[N]; //存储数据
void jianshu(int u, int l, int r)
{ //建树
tr[u].l = l, tr[u].r = r;
if (l == r)
{
tr[u].mx = a[l];
return;
}
int mid = (l + r) >> 1;
jianshu(u << 1, l, mid), jianshu(u << 1 | 1, mid + 1, r);
tr[u].mx = max(tr[u << 1].mx, tr[u << 1 | 1].mx);
}
int query(int u, int l, int r)
{ //查询操作
if (tr[u].l >= l && tr[u].r <= r)
return tr[u].mx; //全部包含
int mx = 0;
int mid = (tr[u].l + tr[u].r) >> 1;
if (l <= mid)
mx = query(u << 1, l, r);
if (r > mid)
mx = max(mx, query(u << 1 | 1, l, r));
return mx;
}
signed main()
{
int n, q;
cin >> n >> q;
for (int i = 1; i <= n; i++)
cin >> a[i];
jianshu(1, 1, n);
while (q--)
{
int l, r;
cin >> l >> r;
cout << l << ' ' << r << "max is :" << query(1, l, r) << endl;
}
return 0;
}
标签:int,线段,tr,mid,long,query,mx From: https://www.cnblogs.com/msluli/p/16859014.html