目录
A Simple Problem with Integers
模板题:
线段树:
A Simple Problem with Integers
题意:线段树模板题,求区间和,附有区间修改。
AC代码:
/*---------------------------------
*File name: 线段树-A-A_Simple_Problem.cpp
*Creation date: 2020-06-07 08:20
*Link: https://vjudge.net/contest/377030#problem/A
*-------------------------------*/
#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#include<string>
#include<cstring>
#include<iostream>
#include<algorithm>
#define fi first
#define se second
#define pb push_back
#define LL long long
#define PII pair<int, int>
#define Pque priority_queue
using namespace std;
const int maxn = 1e5 + 5;
const int inf = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
const double EPS = 1e-8;
int n, q;
struct Tree{
LL l, r, w;
LL f;
}t[maxn << 2];
void Build(int l, int r, int k){
t[k].l = l, t[k].r = r;
if(l == r){
scanf("%lld", &t[k].w);
return;
}
int mid = l + r >> 1;
Build(l, mid, k << 1);
Build(mid + 1, r, k << 1 | 1);
t[k].w = t[k << 1].w + t[k << 1 | 1].w;
}
void down(int k){
t[k << 1].f += t[k].f;
t[k << 1 | 1].f += t[k].f;
t[k << 1].w += (t[k<<1].r - t[k<<1].l + 1) * t[k].f;
t[k << 1 | 1].w += (t[k<<1|1].r - t[k<<1|1].l + 1) * t[k].f;
t[k].f = 0;
}
LL query(int l, int r, int k, int L, int R){
if(L <= l && r <= R) return t[k].w;
if(t[k].f) down(k);
int mid = l + r >> 1;
LL ans = 0;
if(L <= mid) ans += query(l, mid, k << 1, L, R);
if(R > mid) ans += query(mid + 1, r, k<<1|1, L, R);
return ans;
}
void Update(int l, int r, int k, int L, int R, LL x){
if(L <= l && r <= R){
t[k].f += x;
t[k].w += x * (r - l + 1);
return;
}
if(t[k].f) down(k);
int mid = l + r >> 1;
if(L <= mid) Update(l, mid, k << 1, L, R, x);
if(R > mid) Update(mid + 1, r, k<<1|1, L, R, x);
t[k].w = t[k << 1].w + t[k << 1 | 1].w;
}
int main(){
scanf("%d %d", &n, &q);
Build(1, n, 1);
for(int i = 1; i <= q; ++i){
char s;
scanf(" %c", &s);
if(s == 'Q'){
int l, r;
scanf("%d %d", &l, &r);
printf("%lld\n", query(1, n, 1, l, r));
}
else{
int l, r;
LL x;
scanf("%d %d %lld", &l, &r, &x);
Update(1, n, 1, l, r, x);
}
}
return 0;
}
主席树无修改:
K-th Number
题意:区间第k大。
AC代码:
/*---------------------------------
*File name: 主席树-A-K-th_Number.cpp
*Creation date: 2020-06-06 12:09
*Link:https://vjudge.net/contest/377159#problem/A
*-------------------------------*/
#include<set>
#include<map>
#include<cmath>
#include<queue>
#include<vector>
#include<cstdio>
#i