Codeforces 570D TREE REQUESTS dfs序+树状数组

本文介绍了一种使用树状数组结合DFS序处理树形结构查询问题的方法,具体解决的是如何判断特定子树中指定深度的节点所包含的字母是否能构成回文串的问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

链接

题解链接:点击打开链接

题意:

给定n个点的树,m个询问

下面n-1个数给出每个点的父节点,1是root

每个点有一个字母

下面n个小写字母给出每个点的字母。

下面m行给出询问:

询问形如 (u, deep) 问u点的子树中,距离根的深度为deep的所有点的字母能否在任意排列后组成回文串,能输出Yes.

思路:dfs序,给点重新标号,dfs进入u点的时间戳记为l[u], 离开的时间戳记为r[u], 这样对于某个点u,他的子树节点对应区间都在区间 [l[u], r[u]]内。

把距离根深度相同的点都存到vector里 D[i] 表示深度为i的所有点,在dfs时可以顺便求出。

把询问按深度排序,query[i]表示所有深度为i的询问。

接下来按照深度一层层处理。

对于第i层,把所有处于第i层的节点都更新到26个树状数组上。

然后处理询问,直接查询树状数组上有多少种字母是奇数个的,显然奇数个字母的种数要<=1

处理完第i层,就把树状数组逆向操作,相当于清空树状数组

注意的一个地方就是 询问的深度是任意的,也就是说可能超过实际树的深度,也可能比当前点的深度小。。所以需要初始化一下答案。。


#pragma comment(linker, "/STACK:1024000000,1024000000")
#include <stdio.h>  
#include <iostream>  
#include <algorithm>  
#include <sstream>  
#include <stdlib.h>  
#include <string.h>  
#include <limits.h>  
#include <vector>  
#include <string>  
#include <time.h>  
#include <math.h>  
#include <iomanip>  
#include <queue>  
#include <stack>  
#include <set>  
#include <map>  
const int inf = 1e9;
const double eps = 1e-8;
const double pi = acos(-1.0);
template <class T>
inline bool rd(T &ret) {
	char c; int sgn;
	if (c = getchar(), c == EOF) return 0;
	while (c != '-' && (c<'0' || c>'9')) c = getchar();
	sgn = (c == '-') ? -1 : 1;
	ret = (c == '-') ? 0 : (c - '0');
	while (c = getchar(), c >= '0'&&c <= '9') ret = ret * 10 + (c - '0');
	ret *= sgn;
	return 1;
}
template <class T>
inline void pt(T x) {
	if (x < 0) { putchar('-'); x = -x; }
	if (x > 9) pt(x / 10);
	putchar(x % 10 + '0');
}
using namespace std;
const int N = 5e5 + 100;
typedef long long ll;
typedef pair<int, int> pii;
struct BIT {
	int c[N], maxn;
	void init(int n) { maxn = n; memset(c, 0, sizeof c); }
	inline int Lowbit(int x) { return x&(-x); }
	void change(int i, int x)//i点增量为x
	{
		while (i <= maxn)
		{
			c[i] += x;
			i += Lowbit(i);
		}
	}
	int sum(int x) {//区间求和 [1,x]
		int ans = 0;
		for (int i = x; i >= 1; i -= Lowbit(i))
			ans += c[i];
		return ans;
	}
	int query(int l, int r) {
		return sum(r) + sum(l - 1); 
	}
}t[26];
int n, m;
char s[N];
vector<int>G[N], D[N];
int l[N], r[N], top;
vector<pii>query[N];
bool ans[N];
void dfs(int u, int fa, int dep) {
	D[dep].push_back(u);
	l[u] = ++top;
	for (auto v : G[u])
		if (v != fa)dfs(v, u, dep + 1);
	r[u] = top;
}
int main() {
	rd(n); rd(m);
	fill(ans, ans + m + 10, 1);
	for (int i = 0; i < 26; i++) t[i].init(n);
	for (int i = 2, u; i <= n; i++)rd(u), G[u].push_back(i);
	top = 0;
	dfs(1, 1, 1);
	scanf("%s", s + 1);
	for (int i = 1, u, v; i <= m; i++) {
		rd(u); rd(v); query[v].push_back(pii(u, i));
	}
	for (int i = 1; i <= n; i++)
	{
		if (D[i].size() == 0)break;
		for (auto v : D[i])	t[s[v] - 'a'].change(l[v], 1);
		
		for (pii Q : query[i])
		{
			int ou = 0;
			for (int j = 0; j < 26; j++)
			{
				if (t[j].query(l[Q.first], r[Q.first]))
					ou += t[j].query(l[Q.first], r[Q.first]) & 1;
			}
			ans[Q.second] = ou <= 1;
		}
		for (auto v : D[i])	t[s[v] - 'a'].change(l[v], -1);
	}
	for (int i = 1; i <= m; i++)ans[i] ? puts("Yes") : puts("No");

	return 0;
}

D. Tree Requests
time limit per test
2 seconds
memory limit per test
256 megabytes
input
standard input
output
standard output

Roman planted a tree consisting of n vertices. Each vertex contains a lowercase English letter. Vertex 1 is the root of the tree, each of the n - 1 remaining vertices has a parent in the tree. Vertex is connected with its parent by an edge. The parent of vertex i is vertex pi, the parent index is always less than the index of the vertex (i.e., pi < i).

The depth of the vertex is the number of nodes on the path from the root to v along the edges. In particular, the depth of the root is equal to 1.

We say that vertex u is in the subtree of vertex v, if we can get from u to v, moving from the vertex to the parent. In particular, vertex v is in its subtree.

Roma gives you m queries, the i-th of which consists of two numbers vihi. Let's consider the vertices in the subtree vi located at depthhi. Determine whether you can use the letters written at these vertices to make a string that is a palindrome. The letters that are written in the vertexes, can be rearranged in any order to make a palindrome, but all letters should be used.

Input

The first line contains two integers nm (1 ≤ n, m ≤ 500 000) — the number of nodes in the tree and queries, respectively.

The following line contains n - 1 integers p2, p3, ..., pn — the parents of vertices from the second to the n-th (1 ≤ pi < i).

The next line contains n lowercase English letters, the i-th of these letters is written on vertex i.

Next m lines describe the queries, the i-th line contains two numbers vihi (1 ≤ vi, hi ≤ n) — the vertex and the depth that appear in thei-th query.

Output

Print m lines. In the i-th line print "Yes" (without the quotes), if in the i-th query you can make a palindrome from the letters written on the vertices, otherwise print "No" (without the quotes).

Sample test(s)
input
6 5
1 1 1 3 3
zacccd
1 1
3 3
4 1
6 1
1 2
output
Yes
No
Yes
Yes
Yes
Note

String s is a palindrome if reads the same from left to right and from right to left. In particular, an empty string is a palindrome.

Clarification for the sample test.

In the first query there exists only a vertex 1 satisfying all the conditions, we can form a palindrome "z".

In the second query vertices 5 and 6 satisfy condititions, they contain letters "с" and "d" respectively. It is impossible to form a palindrome of them.

In the third query there exist no vertices at depth 1 and in subtree of 4. We may form an empty palindrome.

In the fourth query there exist no vertices in subtree of 6 at depth 1. We may form an empty palindrome.

In the fifth query there vertices 2, 3 and 4 satisfying all conditions above, they contain letters "a", "c" and "c". We may form a palindrome "cac".


<think>首先,用户的问题是关于一个算法问题的:使用“堆优化Dijkstra + bool数组标记 + dist数组记录权重”是否能通过一道题。但用户没有指定具体的题目,所以我需要基于上下文来推测。之前的对话是关于最小生成树的,特别是Kruskal算法,但这次用户提到了Dijkstra算法,这是用于单源最短路径的。 用户的问题似乎是针对某个具体的编程问题,但这里没有提供题目描述。所以,在回答时,我需要给出一般性的建议,并假设这是一个最短路径问题。 关键元素: - **堆优化Dijkstra**:这是Dijkstra算法的优化版本,使用优先队列(通常是堆)来高效地选择下一个要处理的节点。 - **bool数组标记**:这通常是一个布尔数组(如`visited`数组),用于标记节点是否已被访问过,以避免重复处理。 - **dist数组记录权重**:`dist`数组存储从源点到每个节点的最短距离。 在标准Dijkstra算法中,这些组件是常见的: - 堆优化:减少时间复杂度,从O(V^2)到O(E + V log V)。 - bool数组:用于标记节点是否已确定最短路径。 - dist数组:存储当前已知的最短距离。 所以,对于大多数最短路径问题(尤其是正权重图),这个组合应该是有效的。 现在,回答结构: 1. **回答用户的问题**:我需要确认是否这个组合能通过题目。既然没有具体题目,我可以说在一般情况下,对于单源最短路径问题(非负权重),这个方法是标准且高效的。但如果有特定约束(如负权重、大图等),可能需要调整。 2. **提供代码示例**:用户之前的示例中有Python代码,所以我应该给出一个简单的Dijkstra算法实现,使用堆优化、bool数组和dist数组。 3. **提出3-5个相关问题**:在末尾,必须以“§§相关问题§§”开头,然后列出问题。问题应该基于用户的问题和我的回答。 用户消息的最后部分:"堆优化dijstra+bool数组标记+dist数组记录权重,是否能通过这道题"。这里的“这道题”可能指的是一个隐含的题目,但从上下文看,似乎是通用的。或许是之前的“牧场”问题,但Dijkstra用于最短路径,不是MST。 在之前的对话中,用户提到了“枚举牧场作为起点”,这可能暗示一个需要从每个节点计算最短路径的问题,比如所有对最短路径或多源最短路径。但Dijkstra通常是单源的。如果用户想从每个起点运行Dijkstra,那可能会用到堆优化版本。 所以,在回答中,我应该: - 解释堆优化Dijkstra的适用性。 - 给出一个代码示例。 - 讨论在枚举起点时的情况。 代码示例:我将写一个Python函数,实现堆优化的Dijkstra算法。 伪代码或实际代码: ```python import heapq def dijkstra(graph, start): n = len(graph) dist = [float('inf')] * n dist[start] = 0 visited = [False] * n # bool数组标记 heap = [(0, start)] # (distance, node) while heap: d, node = heapq.heappop(heap) if visited[node]: continue visited[node] = True for neighbor, weight in graph[node]: new_dist = d + weight if new_dist < dist[neighbor]: dist[neighbor] = new_dist heapq.heappush(heap, (new_dist, neighbor)) return dist ``` 在这个代码中: - `graph` 是一个邻接表,例如 `graph[i]` 是列表的元组 `(neighbor, weight)`。 - 使用 `heapq` 实现最小堆。 - `visited` 数组确保每个节点只处理一次。 - `dist` 数组记录最短路径权重。 现在,回答是否能通过题目:一般来说,对于非负权重图,这个算法是正确且高效的。但如果题目有负权重,Dijkstra可能不适用(需要Bellman-Ford)。如果图很大,堆优化是必要的。如果题目要求多源,可能需要多次调用Dijkstra。 最后,提出相关问题: 1. 堆优化Dijkstra算法的时间复杂度是多少? 2. 如果图中存在负权边,Dijkstra算法还能使用吗? 3. 如何修改代码以记录最短路径本身,而不仅仅是距离? 4. 在稀疏图和稠密图中,堆优化Dijkstra的性能如何比较? 5. 如果从每个节点运行Dijkstra,总时间复杂度是多少? 确保3-5个问题。 输出格式: - 先回答问题。 - 然后代码块(用```python ... ```)。 - 然后“§§相关问题§§”开头,列出问题。 完整回答: 首先,解释是否能通过:是的,对于大多数单源最短路径问题(非负权重),这个组合是有效的。 然后,提供代码。 最后,相关问题。</think>基于您的查询,使用“堆优化Dijkstra + bool数组标记 + dist数组记录权重”的方法,在解决单源最短路径问题(图边权重非负)时是标准且高效的。该组合能通过大多数相关题目(如LeetCode、CodeForces中的最短路径问题),原因如下: - **堆优化Dijkstra**:使用优先队列(最小堆)高效选择下一个节点,时间复杂度优化为O(E + V log V),适合稀疏图。 - **bool数组标记**:记录节点是否被访问(`visited`数组),避免重复处理。 - **dist数组**:存储从源点到各节点的最短距离。 在非负权重图中,该方法是正确的。但如果题目有特殊约束(如负权重、大输入规模或需多源处理),可能需要调整(例如负权重需用Bellman-Ford)。以下是一个Python实现示例: ```python import heapq def dijkstra(graph, start): n = len(graph) dist = [float('inf')] * n # 初始化dist数组,记录权重 dist[start] = 0 visited = [False] * n # bool数组标记节点访问状态 heap = [(0, start)] # 最小堆:(距离, 节点) while heap: d, node = heapq.heappop(heap) if visited[node]: # 跳过已访问节点 continue visited[node] = True for neighbor, weight in graph[node]: new_dist = d + weight if new_dist < dist[neighbor]: dist[neighbor] = new_dist heapq.heappush(heap, (new_dist, neighbor)) return dist # 示例使用:graph为邻接表,graph[0] = [(1, 2), (2, 5)] 表示节点0到1的边权重为2。 # result = dijkstra(graph, 0) # 从节点0开始 ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值