题意:一棵N个结点(编号从0开始)的树,根结点为0,求到根结点的距离大于D的结点个数(0 < 测试组数T <= 10, 0<N<=100000, 0<D<N)。
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=4707
——>>统计吧。。。
#include <cstdio> #include <cstring> using namespace std; const int maxn = 100000 + 10; int D, head[maxn], nxt[maxn<<1], v[maxn<<1], ecnt, d[maxn], ret; void init(){ memset(head, -1, sizeof(head)); ecnt = 0; ret = 0; } void addEdge(int uu, int vv){ v[ecnt] = vv; nxt[ecnt] = head[uu]; head[uu] = ecnt; ecnt++; } void dfs(int x, int fa){ if(d[x] > D) ret++; for(int e = head[x]; e != -1; e = nxt[e]) if(v[e] != fa){ d[v[e]] = d[x] + 1; dfs(v[e], x); } } void solve(){ d[0] = 0; dfs(0, -1); printf("%d\n", ret); } int main() { int T, N, uu, vv; scanf("%d", &T); while(T--){ init(); scanf("%d%d", &N, &D); for(int i = 0; i < N-1; i++){ scanf("%d%d", &uu, &vv); addEdge(uu, vv); addEdge(vv, uu); } solve(); } return 0; }