Codeforces Round #321 (Div. 2) C. Kefa and Park | 书脊
http://codeforces.com/contest/580/problem/C
题目大意: 给一个tree, tree上有几个mark的节点, 连续走m个mark的节点就不能继续往下走了. 问你能走到多少个leaf. leaf的定义是没有child的节点.
分析: 首先找出mark的节点的index, 存一下, 然后找到leaf的index, 存一下, 找leaf时, 看一下相邻的节点个数就可以判断出那个是leaf, 如果节点个数是1(只有父节点), 那么就是leaf. 然后从root dfs一下, 每次搜到一个mark的节点就计数, 达到m个就return, 然后遍历每个leaf节点, 如果这些节点都visited了, 那么就res++.
http://codeforces.com/contest/580/problem/C
Kefa decided to celebrate his first big salary by going to the restaurant.
He lives by an unusual park. The park is a rooted tree consisting of n vertices with the root at vertex 1. Vertex 1 also contains Kefa's house. Unfortunaely for our hero, the park also contains cats. Kefa has already found out what are the vertices with cats in them.
The leaf vertices of the park contain restaurants. Kefa wants to choose a restaurant where he will go, but unfortunately he is very afraid of cats, so there is no way he will go to the restaurant if the path from the restaurant to his house contains more than m consecutive vertices with cats.
Your task is to help Kefa count the number of restaurants where he can go.
Input
The first line contains two integers, n and m (2 ≤ n ≤ 105, 1 ≤ m ≤ n) — the number of vertices of the tree and the maximum number of consecutive vertices with cats that is still ok for Kefa.
The second line contains n integers a1, a2, ..., an, where each ai either equals to 0 (then vertex i has no cat), or equals to 1(then vertex i has a cat).
Next n - 1 lines contains the edges of the tree in the format "xi yi" (without the quotes) (1 ≤ xi, yi ≤ n, xi ≠ yi), where xi and yiare the vertices of the tree, connected by an edge.
It is guaranteed that the given set of edges specifies a tree.
input
4 1 1 1 0 0 1 2 1 3 1 4
output
2
分析: 首先找出mark的节点的index, 存一下, 然后找到leaf的index, 存一下, 找leaf时, 看一下相邻的节点个数就可以判断出那个是leaf, 如果节点个数是1(只有父节点), 那么就是leaf. 然后从root dfs一下, 每次搜到一个mark的节点就计数, 达到m个就return, 然后遍历每个leaf节点, 如果这些节点都visited了, 那么就res++.
int res = 0;
ArrayList<Integer>[] g;
ArrayList<Integer> leaf;
int[] cat;
int n;
int m;
boolean[] visited;
public void solve(int testNumber, InputReader in, OutputWriter out) {
n = in.readInt();
m = in.readInt();
g = new ArrayList[n];
visited = new boolean[n];
leaf = new ArrayList<>();
cat = IOUtils.readIntArray(in, n);
for (int i = 0; i < n; i++) {
g[i] = new ArrayList<>();
}
for (int i = 1; i < n; i++) {
int x = in.readInt();
int y = in.readInt();
x--;
y--;
g[x].add(y);
g[y].add(x);
}
for (int i = 1; i < n; i++)
if (g[i].size() == 1)
leaf.add(i);
dfs(0,0);
for(Integer i:leaf)
if(visited[i])
res++;
out.print(res);
}
private void dfs(int v, int c) {
if (cat[v] == 1)
c++;
else
c = 0;
if (c > m)
return;
visited[v] = true;
for (int i :g[v]) {
if (!visited[i])
dfs(i, c);
}
return;
}
Read full article from Codeforces Round #321 (Div. 2) C. Kefa and Park | 书脊