线段树+主席树练习题解

目录

 

模板题:

线段树:

A Simple Problem with Integers

主席树无修改:

K-th Number

可修改主席树(树状数组套主席树)

P2617 Dynamic Rankings

简单题:

简单线段树:

Balanced Lineup

简单主席树:

Click Here

中等:

中等线段树:

Mayor's posters


模板题:

线段树:

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
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值