【CF580C】Kefa and Park dfs

Kefa and Park dfs

  • 题目大意
  • 题目链接
  • 代码

题目大意

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.
需要注意的是这里是不能连续碰到超过m个猫,一开始题目没有读懂

题目链接

传送门

代码

#include 
#include 
#include 
using namespace std;
const int N = 2e5 + 10;
int n, m, cnt, ans;
int head[N], cat[N], rud[N],sum[N];
struct edge{
    int to, nxt;
}e[N << 1];

inline int read(){
    int x = 0, op = 1;
    char ch = getchar();
    while (!isdigit(ch)){
        if (ch == '-') op = -1;
        ch = getchar();
    }
    while (isdigit(ch)){
        x = (x << 1) + (x << 3) + (ch ^ 48);
        ch = getchar();
    }
    return x * op;
}

inline void add(int u, int v){
    e[++cnt] = {v, head[u]};
    head[u] = cnt;
}

void dfs(int u,int fa,int num)
{
    if(cat[u]) num++;
    else num = 0;

    if (num > m) return;
    if (rud[u] == 1 && u != 1)
        ans++;
    for (int i = head[u]; i; i = e[i].nxt) {
        int v = e[i].to;
        if (v == fa) continue;
        dfs(v, u, num);
    }
}

int main() {
    n = read(), m = read();
    for (int i = 1; i <= n; ++i) {
        cat[i] = read();
    }
    for (int i = 0, x ,y; i < n - 1; ++i) {
        x = read(), y = read();
        add(x, y), add(y, x);
        rud[x]++;
        rud[y]++;
    }
    dfs(1, -1, 0);
    printf("%d\n", ans);
    return 0;
}

你可能感兴趣的:(树形结构,dfs)