您的位置:首页 > 产品设计 > UI/UE

Codeforces Round #316 Tree Requests

2015-09-12 16:41 441 查看
题目链接

题意:给一棵树,树上每个节点都有一个字母,问在某个节点的子树中,到根的深度为d的所有节点上的字母任意排列,能否形成一个回文串。

思路:将树改成线性,按访问顺序给新的标号,并记录一棵子树的起始点,以及最大的子孙节点,同时将每个节点按照其深度放进一个数组中,这样每个深度数组都是有序的,并且同一棵子树上节点一定是连续的,然后就可以用二分寻找某一子树的某个深度节点的所在范围,并通过记录前缀和的方式O(1)时间内算出答案。

#include <cstdio>
#include <cstring>
#include <vector>
#include <algorithm>
using namespace std;
const int M = 500005;
int in[M], out[M];
char str[M], s[M];
vector<int> p[M], depth[M], presum[M];
inline int lowbit(int a){
return a & (-a);
}
int idx = 0, ch[M];
void dfs(int now, int dep){
in[now] = ++idx;
s[idx] = str[now];
depth[dep].push_back(idx);
for(int i = 0; i < p[now].size(); i++)
dfs(p[now][i], dep + 1);
out[now] = idx;
}
bool judge(int a){
return (a - lowbit(a)) == 0;
}
main() {
int n, m;
scanf("%d %d", &n, &m);
for(int i = 2; i <= n; i++){
int a;
scanf("%d", &a);
p[a].push_back(i);
}
scanf("%s", &str[1]);
dfs(1, 1);
for(int i = 1; i <= n; i++){
for(int j = 0; j < depth[i].size(); j++){
int v = depth[i][j];
if(j == 0) presum[i].push_back(1 << (s[v] - 'a'));
else presum[i].push_back((1 << (s[v] - 'a')) ^ presum[i][j - 1]);
}
}
for(int i = 0; i < m; i++){
int a, b;
scanf("%d %d", &a, &b);
int l = upper_bound(depth[b].begin(), depth[b].end(), in[a] - 1) - depth[b].begin();
int r = upper_bound(depth[b].begin(), depth[b].end(), out[a]) - depth[b].begin() - 1;
if(r < 0 || l >= depth[b].size()) puts("Yes");
else {
int t1, t2;
if(l == 0) t1 = 0;
else t1 = presum[b][l - 1];
t2 = presum[b][r];
if(judge(t1 ^ t2)) puts("Yes");
else puts("No");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: