之前做过一个类似的。
https://blog.csdn.net/qq_44115065/article/details/105978281
对于这个题目:只需要在树状数组上进行单点修改就可以。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <queue>
#include <cmath>
#include <string>
#include <vector>
#include <stack>
#include <map>
#include <sstream>
#include <cstring>
#include <set>
#include <cctype>
#include <bitset>
#define IO \
ios::sync_with_stdio(false); \
// cin.tie(0); \
// cout.tie(0);
using namespace std;
typedef long long LL;
typedef unsigned long long ULL;
const int maxn = 1e6 + 100;
const int maxm = 1e6 + 10;
const LL INF = 0x3f3f3f3f3f3f3f3f;
const int inf = 0x3f3f3f3f;
const LL mod = 1e9 + 7;
int dis[8][2] = {0, 1, 1, 0, 0, -1, -1, 0, 1, -1, 1, 1, -1, 1, -1, -1};
int head[maxn], n, k, tim;
int siz[maxn], dfn[maxn], in[maxn];
int a[maxn], c[maxn];
struct Edge
{
int next;
int to;
} e[maxm];
int lowbit(int x)
{
return x & (-x);
}
void add(int u, int v)
{
e[k].next = head[u];
e[k].to = v;
head[u] = k++;
}
void DFS(int u, int fa)
{
dfn[u] = ++tim;
siz[u] = 1;
for (int i = head[u]; i != -1; i = e[i].next)
{
int v = e[i].to;
if (v == fa)
continue;
DFS(v, u);
siz[u] += siz[v];
}
}
void update(int x, int k) // x 为修改为止 k为位置上的增加值
{
while (x <= n)
{
c[x] += k;
x += lowbit(x);
}
}
int ask(int i)
{
int ans = 0;
while (i >= 1)
{
ans += c[i];
i -= lowbit(i);
}
return ans;
}
int main()
{
#ifdef ONLINE_JUDGE
#else
freopen("in.txt", "r", stdin);
// freopen("out.txt", "w", stdout);
#endif
IO;
cin >> n;
memset(head, -1, sizeof head);
int x, y, m;
char ch;
for (int i = 0; i < n - 1; i++)
{
cin >> x >> y;
add(x, y);
add(y, x);
}
DFS(1, 0);
for (int i = 1; i <= n; i++)
{
a[i] = 1;
update(i, 1);
}
cin >> m;
while (m--)
{
int i;
cin >> ch >> i;
if (ch == 'C')
{
if (a[i])
{
a[i] = 0;
update(dfn[i], -1);
}
else
{
a[i] = 1;
update(dfn[i], 1);
}
}
else
{
cout << ask(dfn[i] + siz[i] - 1) - ask(dfn[i] - 1) << endl;
}
}
return 0;
}