POJ 3321 Apple Tree(DFS序列+树状数组)

题目传送门

之前做过一个类似的。

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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值