跳到正文

剪贴板

剪贴板 ulw9c0iv

原文
剪贴板信息

剪贴板信息

收录
更新
C++
#include <iostream>
#include <stdio.h>
#include <algorithm>
#include <string.h>
using namespace std;
const int maxn = 1e5 + 5;

template <typename T>
inline void read(T& x){
x = 0; int f = 1; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = -f; c = getchar(); }
while (c >= '0' && c <= '9') { x = (x << 3) + (x << 1) + (c ^ 48), c = getchar(); } x *= f;
}
template <typename T, typename... Args>
inline void read (T &x, Args&... Arg) { read (x), read (Arg...); }

int n,m,num,tot,Time;
int head[maxn],color[maxn],sz[maxn],dfn[maxn],point[maxn];
int ans[maxn],cnt[maxn],Son[maxn];           //cnt[i]:color为i的出现次数,Son记录重儿子
struct Edge{
    int to,next;
}e[maxn << 1];
inline void add(int u,int v){
    e[++num].to = v;
    e[num].next = head[u];
    head[u] = num;
}
inline void Add(int u){
    cnt[color[u]]++;
    if(cnt[color[u]] == 1)
        tot++;
}
inline void Delete(int u){
    cnt[color[u]]--;
    if(cnt[color[u]] == 0)
        tot--;
}
inline void dfs1(int u,int fa){              //统计sz和Son
    dfn[u] = ++Time;
    point[Time] = u;
    sz[u] = 1;
    for(int i=head[u];i;i=e[i].next){
        int v = e[i].to;
        if(v != fa){
            dfs1(v,u);
            sz[u] += sz[v];
            if(sz[v] > sz[Son[u]] || !Son[u])
                Son[u] = v;
        }
    }
}
inline void dfs2(int u,int fa,bool type){
    for(int i=head[u];i;i=e[i].next){
        int v = e[i].to;
        if(v != fa && v != Son[u])              //先遍历轻儿子,得到轻儿子答案,不保留修改
            dfs2(v,u,0);
    }
    if(Son[u])
        dfs2(Son[u],u,1);                       //再遍历重儿子,得到重儿子答案,保留修改
    for(int i=head[u];i;i=e[i].next){           //最后再合并轻儿子答案
        int v = e[i].to;
        if(v != fa && v != Son[u])
            for(int i=dfn[v];i<=dfn[v]+sz[v]-1;i++)
                Add(point[i]);
    }
    Add(u);
    ans[u] = tot;
    if(!type)                                   //消去贡献
        for(int i=dfn[u];i<=dfn[u]+sz[u]-1;i++)
            Delete(point[i]);
}
int main(){

    read(n);
    for(int i=1;i<n;i++){
        int u,v;
        read(u,v);
        add(u,v);
        add(v,u);
    }
    for(int i=1;i<=n;i++)
        read(color[i]);
    dfs1(1,0);
    dfs2(1,0,1);
    read(m);
    while(m--){
        int x;
        read(x);
        printf("%d\n",ans[x]);
    }

    return 0;
}