UVA - 1267 Network
Input
Your program is to read the input from standard input. The input consists of T test cases. The number
of test cases (T) is given in the first line of the input. The first line of each test case contains an integer
n (3 ≤ n ≤ 1, 000) which is the number of nodes of the tree network. The next line contains two
integers s (1 ≤ s ≤ n) and k (k ≥ 1) where s is the VOD server and k is the distance value for ensuring
the quality of service. In the following n − 1 lines, each line contains a pair of nodes which represent
an edge of the tree network.
Output
Your program is to write to standard output. Print exactly one line for each test case. The line should
contain an integer that is the minimum number of the needed replicas.
Sample Input
2
14
12 2
1 2
2 3
3 4
4 5
5 6
7 5
8 5
4 9
10 3
2 12
12 14
13 14
14 11
14
3 4
1 2
2 3
3 4
4 5
5 6
7 5
8 5
4 9
10 3
2 12
12 14
13 14
14 11
Sample Output
1
0
vector建立边关系,如何判断是叶子节点,从任一点dfs范围搜索
#include <cstdio> #include <vector> using namespace std; const int MAX = 1000 + 5; int cover[MAX], fa[MAX], n, s, k; vector<int> gr[MAX], nodes[MAX];//gr是边,nodes是该深度的叶子节点 void dfs(int u, int f, int d); void dfs2(int u, int f, int d); int main() { int T; scanf("%d", &T); for (int base = 0; base < T; ++base) { for (int i = 0; i < MAX; ++i) { cover[i] = 0, fa[i] = 0, gr[i].clear(), nodes[i].clear(); } scanf("%d%d%d", &n, &s, &k); //有回车可以无视 for (int i = 0; i < n - 1; ++i) { int u, v; scanf("%d%d", &u, &v); //建立双边关系 gr[u].push_back(v); gr[v].push_back(u); } dfs(s, -1, 0); int ans = 0; for (int h = n - 1; h > k; --h) { //从最深开始 for (int j = 0; j < nodes[h].size(); ++j) { int v = nodes[h][j]; if (cover[v]) continue; for (int i = 0; i < k; ++i) { v = fa[v]; } dfs2(v, -1, 0); //从该节点dfs ans++; } } printf("%d\n", ans); } } void dfs2(int u, int f, int d) { cover[u] = 1; for (int i = 0; i < gr[u].size(); ++i) { int v = gr[u][i]; if (v != f and d < k) dfs2(v, u, d + 1); } } void dfs(int u, int f, int d) { fa[u] = f; //建立父节点 int nc = gr[u].size(); if (nc == 1 and d > k) nodes[d].push_back(u); //是叶子节点存进去 for (int i = 0; i < nc; ++i) { int v = gr[u][i]; if (v != f) dfs(v, u, d + 1); //不是叶子节点继续地柜 } }