Apple Tree
Apple Tree
SCUACM2022集训前训练-数据结构 - Virtual Judge (vjudge.net)
dfs序 + 树状数组
注意以后存边时写,效率较高
vector<vector<int> > G(N);
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <cmath>
#include <cstdio>
using namespace std;
typedef long long ll;
const int N = 1e5 + 10;
vector<vector<int> > G(N);
int tim, tin[N], tout[N];
int tr[N];
int n;
int lowbit(int x)
{
return x & -x;
}
int query(int idx)
{
int ans = 0;
for (int i = idx; i; i -= lowbit(i))
ans += tr[i];
return ans;
}
void add(int idx, int k)
{
for (int i = idx; i <= n; i += lowbit(i))
tr[i] += k;
}
void add_edge(int u, int v)
{
G[u].push_back(v);
}
void dfs(int u, int fa)
{
tin[u] = ++tim;
for (int i = 0; i < G[u].size(); i++)
{
int v = G[u][i];
if (v == fa)
continue;
dfs(v, u);
}
tout[u] = tim;
}
int main()
{
scanf("%d", &n);
for (int i = 1; i < n; i++)
{
int u, v;
scanf("%d%d", &u, &v);
add_edge(u, v), add_edge(v, u);
}
dfs(1, -1);
for (int i = 1; i <= n; i++)
add(i, 1);
int q;
scanf("%d", &q);
while(q--)
{
getchar();
char op = getchar();
int u;
scanf("%d", &u);
if (op == 'Q')
{
int ans = query(tout[u]) - query(tin[u] - 1);
printf("%d\n", ans);
}
else
{
int t = query(tin[u]) - query(tin[u] - 1);
if (t == 1)
add(tin[u], -1);
else
add(tin[u], 1);
}
}
return 0;
}