线段树题单练习题解
线段树题单练习题解
1 hdu 1166
#include <bits/stdc++.h>
using namespace std;
const int N = 5e4+5;
typedef long long ll;
int t, n, p, a, b;
char op[10];
ll val;
ll tree[N<<2];
void push_up(int rt){
tree[rt] = tree[rt<<1] + tree[rt<<1|1];
}
void build(int rt, int l, int r){
if(l==r){
scanf("%lld", &tree[rt]);
}else{
int mid = (l+r)>>1;
build(rt<<1, l, mid);
build(rt<<1|1, mid+1, r);
push_up(rt);
}
}
void modify(int rt, int l, int r, int p, ll v){
tree[rt] += v;
if(l==r) return;
int mid = (l+r)>>1;
if(p <= mid) modify(rt<<1, l, mid, p, v);
else modify(rt<<1|1, mid+1, r, p, v);
push_up(rt);
}
ll query(int rt, int l, int r, int ql, int qr){
if(ql <= l && qr >= r){
return tree[rt];
}else{
ll ans = 0;
int mid = (l+r)>>1;
if(ql <= mid){
ans += query(rt<<1, l, mid, ql, qr);
}
if(qr > mid){
ans += query(rt<<1|1, mid+1, r, ql, qr);
}
return ans;
}
}
int main(){
scanf("%d", &t);
for(int _ = 1; _ <= t; ++_){
printf("Case %d:\n", _);
scanf("%d", &n);
build(1, 1, n);
while (1) {
getchar();
scanf("%s", op);
if(*op == 'Q'){
scanf("%d%d", &a, &b);
printf("%lld\n", query(1, 1, n, a, b));
}else if(*op == 'A'){
scanf("%d%lld", &p, &val);
modify(1, 1, n, p, val);
}else if(*op == 'S'){
scanf("%d%lld", &p, &val);
modify(1, 1, n, p, -val);
}else{
break;
}
}
}
return 0;
}
hdu 1754
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int N = 2e5+5;
int n, m, a, b, p;
ll v;
char op[10];
ll arr[N];
ll tree[N<<2];
inline ll Max(ll a, ll b){
return a>b?a:b;
}
void build(int rt, int l, int r){
if(l==r){
scanf("%lld", &tree[rt]);
}else{
int mid = l+r>>1;
build(rt<<1, l, mid);
build(rt<<1|1, mid+1, r);
tree[rt] = Max(tree[rt<<1], tree[rt<<1|1]);
}
}
void modify(int rt, int l, int r, int p, ll v){
tree[rt] = Max(tree[rt], v);
if(l==r)return;
int mid = l+r>>1;
if(p <= mid) modify(rt<<1, l, mid, p, v);
else modify(rt<<1|1, mid+1, r, p, v);
}
ll query(int rt, int l, int r, int ql, int qr){
if(ql <= l && qr >= r) return tree[rt];
else{
ll ans = 0;
int mid = l+r>>1;
if(ql <= mid){
ans = query(rt<<1, l, mid, ql, qr);
}
if(qr > mid){
ans = Max(ans, query(rt<<1|1, mid+1, r, ql, qr));
}
return ans;
}
}
int main(){
while(scanf("%d%d", &n, &m) != EOF){
build(1, 1, n);
while(m--){
getchar();
scanf("%s", op);
if(*op == 'Q'){
scanf("%d%d", &a, &b);
printf("%lld\n", query(1, 1, n, a, b));
}else{
scanf("%d%lld", &p, &v);
modify(1, 1, n, p, v);
}
}
}
return 0;
}
---- suffer now and live the rest of your life as a champion ----