Auxiliary Set
题目链接:
http://acm.split.hdu.edu.cn/showproblem.php?pid=5927
解题思路:
题目大意:
给你一个根节点为1的树,定义一个节点为重要的节点至少满足两个条件中的一个条件:
1:自己本身是重要的点
2:两个以上的子孙是重要的点
接着给你q组询问,给出m个不重要的点,让你输出树上有多少重要的点?
算法思想:
对unimportant node按逆DFS序排序.
接着遍历此集合, 同时对每个节点u进行维护,维护u满足如下条件的儿子v的数目:
子树v中不全是un-node。
不妨将此数目记作cnt[u],维护的方法是:
对某个u, 若 cnt[u]==0 就 --cnt[pa[u]]。
最后, 满足 cnt[u]≥2 的u的数目即为所求。
AC代码:
#include <bits/stdc++.h>
using namespace std;
const int N = 100005;
int tail;
int dep[N],pa[N];
int cnt[N],_cnt[N];
vector<int> g[N],un;//un is unimportant nodes
void dfs(int u,int fa){
dep[u] = ++tail;
pa[u] = fa;
for(auto v:g[u]){
if(v != fa){
++cnt[u];
dfs(v,u);
}
}
}
bool cmp(int x,int y){
return dep[x] > dep[y];
}
int main(){
int t = 0,T;
scanf("%d",&T);
while(T--){
int n,q;
scanf("%d%d",&n,&q);
for(int i = 0; i <= n; ++i){
g[i].clear();
cnt[i] = 0;
}
int u,v;
for(int i = 1; i < n; ++i){
scanf("%d%d",&u,&v);
g[u].push_back(v);
g[v].push_back(u);
}
tail = 0;
dfs(1,0);
printf("Case #%d:\n", ++t);
while(q--){
int x,m;
scanf("%d",&m);
un.clear();
while(m--){
scanf("%d",&x);
un.push_back(x);
}
sort(un.begin(),un.end(),cmp);
for(auto x:un){
_cnt[x] = cnt[x];
}
for(auto x:un){
if(_cnt[x] == 0){
--_cnt[pa[x]];
}
}
int ans = 0;
for(auto x:un){
ans += _cnt[x] >= 2;
}
ans += n-un.size();
printf("%d\n",ans);
}
}
return 0;
}