ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

2021牛客暑期多校训练营9-倍增、主席树、dfs序

2022-03-20 19:04:27  阅读:139  来源: 互联网

标签:int mid tr 多校 dfs st 牛客 maxn


题目链接

题意

在一个国家中有 n n n个城市, 1 1 1是该国家的首都,这个国家的结构可以看作一颗树。每个国家都有一个温度,越靠近首都的城市温度越高;现在有 q q q次查询,每次询问给出一个点,表示在该城市爆发病毒,并且病毒可以存活的温度范围是 [ l , r ] [l, r] [l,r],问该病毒最多可以扩散到多少城市。

思路

  • 对于爆发病毒的城市,我们可以根据该病毒可存活的温度上限得到离首都最近的城市,可以通过倍增实现,复杂度 l o g n logn logn。
  • 得到可传播最远的城市后,再向它的子树中寻找有多少节点的温度在 [ l , r ] [l,r] [l,r]范围内,这个查询我们可以对该树的 d f s dfs dfs序建立主席树,就可以得到这个点的子树内有多少节点的温度在 [ l , r ] [l,r] [l,r]范围内,复杂度 l o g n logn logn,所以总复杂度为 q l o g n qlogn qlogn。

AC代码

#include<bits/stdc++.h>

using namespace std;
using ll = long long;

const int maxn = 1e5 + 7;

vector<vector<int> > g(maxn);
vector<int> L(maxn), R(maxn), t(maxn), root(maxn, 0), a(maxn, 0);
int cnt = 0, tot = 0, st[20][maxn];

struct HJT {
	int l, r, val;
}tr[maxn << 5];

void insert(int pre, int& now, int l, int r, int x) {
	tr[++cnt] = tr[pre];
	now = cnt;
	tr[now].val++;
	if(l == r) return ;
	int mid = l + r >> 1;
	if(x <= mid) insert(tr[pre].l, tr[now].l, l, mid, x);
	else insert(tr[pre].r, tr[now].r, mid + 1, r, x);
	return ;
}

int query(int pre, int now, int l, int r, int L_, int R_) {
	if(L_ <= l && r <= R_) return tr[now].val - tr[pre].val;
	int mid = l + r >> 1;
	int ans = 0;
	if(mid >= L_) ans += query(tr[pre].l, tr[now].l, l, mid, L_, R_);
	if(mid < R_ ) ans += query(tr[pre].r, tr[now].r, mid + 1, r, L_, R_);
	return ans;
}

void dfs(int x, int fa) {
	L[x] = ++tot;
	st[0][x] = fa;
	insert(root[tot - 1], root[tot], 1, 1e9, t[x]);
	for(int to : g[x]) {
		if(to == fa) continue;
		dfs(to, x);
	}
	R[x] = tot;
}

int main() {
	ios::sync_with_stdio(false);
	cin.tie(nullptr);

	int n;
	cin >> n;
	for(int i = 1;i < n;i++) {
		int u, v;
		cin >> u >> v;
		g[u].push_back(v);
		g[v].push_back(u);
	}
	for(int i = 1;i <= n;i++) cin >> t[i];
	dfs(1, 0);
	for(int j = 1;j < 20;j++) {
		for(int i = 1;i <= n;i++) {
			st[j][i] = st[j - 1][st[j - 1][i]];
		}
	}
	int q;
	cin >> q;
	while(q--) {
		int x, l, r;
		cin >> x >> l >> r;
		if(t[x] >= l && t[x] <= r) {
            for(int i = 19;i >= 0;i--) {
                if(t[st[i][x]] <= r && t[st[i][x]]) {
                    x = st[i][x];
                }
            }
            cout << query(root[L[x] - 1], root[R[x]], 1, 1e9, l, r) << '\n';
		}
		else cout << 0 << '\n';
	}

	return 0;
}

标签:int,mid,tr,多校,dfs,st,牛客,maxn
来源: https://blog.csdn.net/u014711890/article/details/123618667

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有