#include<bits/stdc++.h>
using namespace std;
const int MAXN = 1e4 + 7;
struct Edge{
int to;
int next;
}edge[MAXN * 4];
int head[MAXN],cnt;
int node[MAXN],fa[MAXN],son[MAXN];
void init(){
for(int i = 1;i < MAXN;i++){
head[i] = -1;
edge[i].next = -1;
node[i] = 1;
son[i] = 0;
}
cnt = 0;
}
void addedge(int u,int v){
edge[cnt].to = v;
edge[cnt].next = head[u];
head[u] = cnt++;
}
int dfs(int x,int father){
fa[x] = father;
for(int i = head[x];~i;i = edge[i].next){
if(edge[i].to != father){
son[x]++;
node[x] += dfs(edge[i].to,x);
}
}
return node[x];
}
int n,m,p;
int main(){
cin >> n >> m >> p;
init();
for(int i = 1;i < n;i++){
int x,y;
cin >> x >> y;
addedge(x,y);
addedge(y,x);
}
dfs(m,0);
/*
cout << endl;
for(int i = 1;i <= n;i++){
cout << i << " " << fa[i] << endl;
}
cout << endl;
*/
for(int i = 1;i <= p;i++){
int x;
cin >> x;
int ans;
if(son[x] <= 1){
ans = 0;
}else{
ans = 2;
}
for(int j = head[x];~j;j = edge[j].next){
if(edge[j].to != fa[x]){
ans *= node[edge[j].to];
//cout << edge[j].to << " " << node[edge[j].to] << endl;
}
}
ans = ans + 2 * node[x] - 1;
cout << ans << endl;
}
return 0;
}
代码如上
思路是当 询问的节点的子节点数 小于等于 1 时,ans = (以该节点为根的子树大小 − 1 ) ∗ 2 + 该节点本身
否则 ans = 以该节点的不同儿子为根的子树中的节点 的排列数 + (以该节点为根的子树大小 − 1 ) ∗ 2 + 该节点本身