#6 tle求助
查看原帖
#6 tle求助
821939
zhi_hui_kan_ti_jie楼主2023/4/5 19:06
#include<bits/stdc++.h>
using namespace std;
#define int long long
const int maxn = 1e5 + 10;
int sz[maxn], wson[maxn], top[maxn], dfn[maxn], rdfn[maxn], dep[maxn], fa[maxn];
int vistim; int color[maxn]; int in[maxn];
struct node
{
	int k, id;
};
vector<node>q[maxn];
int ans[maxn];
int much[maxn];
struct edge
{
	int to;
	int nex;
}e[maxn << 1];

int first[maxn], tot;
void add(int a, int b)
{
	e[++tot].to = b;
	e[tot].nex = first[a];
	first[a] = tot;
}
void dfs1(int now, int f, int d)   //剖出重孩子
{
	sz[now] = 1;
	dep[now] = d;
	fa[now] = f;
	in[now] = ++vistim;
	for (int i = first[now]; i; i = e[i].nex)
	{
		int to = e[i].to;
		if (to == f)continue;
		dfs1(to, now, d + 1);
		if (sz[to] > sz[wson[now]]) wson[now] = to;
		sz[now] += sz[to];
	}
	
}
int cnt[27][maxn], mx, sum;
int n, m;
bool check(int d)
{
	int tmp = 0;
	for (int i = 1; i <= 26; i++)
	{
		tmp += cnt[i][d]&1;
	}
	return tmp <= 1;
}
void clear(int now, int fa)   //清空容器
{
	cnt[color[now]][dep[now]]--;
	for (int i = first[now]; i; i = e[i].nex)
	{
		int to = e[i].to;
		if (to == fa)continue;
		clear(to, now);
	}
}

void DFS(int now, int fa, int p)  //暴力枚举轻孩子子树
{
	cnt[color[now]][dep[now]]++;
	for (int i = first[now]; i; i = e[i].nex)
	{
		int to = e[i].to;
		if (to == fa || to == p)continue;
		DFS(to, now, p);
	}
}

void dfs2(int now, int fa)     //启发式合并关键
{
	for (int i = first[now]; i; i = e[i].nex)
	{
		int to = e[i].to;
		if (to == fa)continue;
		if (to != wson[now])
		{
			dfs2(to, now);
			clear(to, now);
		}
	}
	if (wson[now])
		dfs2(wson[now], now);
	DFS(now, fa, wson[now]);
	for (int i = 0; i < q[now].size(); i++)
	{
		ans[q[now][i].id] = check(q[now][i].k);
	}
}
signed main()
{
	ios::sync_with_stdio(0);
	cin.tie(0); cout.tie(0);
	cin >> n >> m;
	int a,b;
	for (int i = 2; i <= n; i++)
	{
		cin >> a; add(a, i); add(i, a);
	}
	char ch;
	for (int i = 1; i <= n; i++)
	{
		cin >> ch; color[i] = ch - 'a' + 1;
	}
	dfs1(1, 0, 1);

	for (int i = 1; i <= m; i++)
	{
		cin >> a>>b;
		q[a].push_back({ b, i });
	}
	dfs2(1, 0);
	for (int i = 1; i <= m; i++)
		cout <<( ans[i]?"Yes\n":"No\n");

	return 0;
}
2023/4/5 19:06
加载中...